Paulos3000 Paulos3000 - 1 year ago 78
Javascript Question

.split() on elements of a sentence string, advanced separator

I want to be able to split a sentence string into an array of individual word strings.

sentenceArr = 'I take the dog to the park'
sentenceArr.split(' ');

Desired result:
['I', 'take', 'the', 'dog', 'to', 'the', 'park']

This is easy if they are just split by spaces as above, but if there are commas or double spaces, or RegExes in the string it can come unstuck.

sentenceArr = 'I take,the dog to\nthe park'
sentenceArr.split(' ');

How can I modify the split() separator argument to account for these irregularities?

Ideally, I want to be able to split anywhere there isn't a letter.

Answer Source

split also takes a regex as argument :

sentenceArr = 'I take,the  dog to\nthe park'
var r= sentenceArr.split(/\W+/);


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download