zumzum
zumzum

Reputation: 20148

javascript string with white spaces how to get an array of strings from it that without whitecaps in it?

I have this string:

myStringtoSplit = "SomeText     123"

I want to get an array that has only 2 things in it: [SomeText,123]

I am now using split():

var array = myStringtoSplit.split(" ");

doing so though gives me an array with length 6. So the array has at [0] = "SomeText" between index 1 and 4 has white spaces and then at index 5 it has "123"

How can I make the resulting array only have the two strings in it with no white spaces?

So I want end up with this:
[SomeText,123]

Upvotes: 0

Views: 136

Answers (1)

Oriol
Oriol

Reputation: 288100

You can use trim to remove whitespaces at the beginning and end.

And then you can use the regex /\s+/, which matches multiple whitespaces, as the separator for split.

"SomeText     123".trim().split(/\s+/)

Note trim was added in EcmaScript5, so you may need to polyfill it.

Upvotes: 3

Related Questions