October 28th, 2016

PowerTip: Know the difference between the .split() method and ‘-split’

Doctor Scripto
Scripter

Summary: Cloud and Datacenter Management MVP, Thomas Rayner, shows how to split a string by using a string instead of just a character.

Hey, Scripting Guy! Question 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?

Hey, Scripting Guy! Answer 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”

The Doctor

Author

The "Scripting Guys" is a historical title passed from scripter to scripter. The current revision has morphed into our good friend Doctor Scripto who has been with us since the very beginning.

0 comments

Discussion are closed.

Feedback