Manny_G
Manny_G

Reputation: 333

How to split only the numbers and/or words from a string into an array in Javascript

I have the string "1, 2, 3" and the string "1, 2, 3 Go!" I would like to split into an array that only includes the numbers or the words without the punctuation.

So first one becomes ["1", "2", "3"]

The second one becomes ["1","2","3", "Go"]

I can get the first one by "1, 2, 3".split(/[^0-9]/).filter(function(value){if(value) return value;}

I use filter because I get ["1", "", "2", "", "3"] when I just use split.

I don't know who to get the second array.

Is there a regular expression pattern that will only split the string into either numbers and or words?

Upvotes: 0

Views: 118

Answers (1)

Dalorzo
Dalorzo

Reputation: 20024

How about this:

"1, 2, 3 Go!".match(/\d+|[a-zA-Z]+/g) //outputs ["1", "2", "3", "Go"]

Upvotes: 3

Related Questions