Skip to content

Converting String to Array

January 19, 2011

I wanted to convert a string to an array that held the words that the string had. if the word is repeated then the element should be also repeated in the array.

myArray = "ABCDEFGHIJKLMNOP".split
myArray = "ABCDEFGHIJKLMNOP".split(//)
=> ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P"]

We can also create an array based on words by using the space (/ /) as the break point:

myArray = "Paris in the Spring".split(/ /)
=> ["Paris", "in", "the", "Spring"]
myArray = "Paris in the Spring".split  
=> ["Paris", "in", "the", "Spring"] 
"Paris in the Spring".split == "Paris in the Spring".split(/ /)  
=> true

Or we can even, perhaps most usefully, convert a comma separated string into an array:

myArray = "Red, Green, Blue, Indigo, Violet".split(/, /)
=> ["Red", "Green", "Blue", "Indigo", "Violet"]

From → Uncategorized

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: