JavaScript break sentence by words

Similar to Ravi’s answer, use match, but use the word boundary \b in the regex to split on word boundaries:

'This is  a test.  This is only a test.'.match(/\b(\w+)\b/g)

yields

["This", "is", "a", "test", "This", "is", "only", "a", "test"]

or

'This is  a test.  This is only a test.'.match(/\b(\w+\W+)/g)

yields

["This ", "is  ", "a ", "test.  ", "This ", "is ", "only ", "a ", "test."]

Leave a Comment