PowerTip: Know the difference between the .split() method and ‘-split’
Summary: Cloud and Datacenter Management MVP, Thomas Rayner, shows how to split a string by using a string instead of just a character.
I am trying to split the string “this is my amazing string” on the pattern “my” by using “this is my amazing string”.split(“my”) but it’s giving me a bunch of garbled stuff back. How do I accomplish my goal?
You’ll have to use –split instead of .split(). Methods like .split() and .trim() take arrays of characters instead of strings. What happened to you is that your pattern, “my”, was treated as an array of characters and “this is my amazing string” was split on all of the “m”s and “y”s in the string. Use the –split method instead.
“this is my amazing string” -split “my”