Search code examples
javascriptarraysstringsplitseparator

.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.


Solution

  • split also takes a regex as argument :

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