JavaScript break sentence by words

Just use split:

var str = "This is an amazing sentence.";
var words = str.split(" ");
console.log(words);
//["This", "is", "an", "amazing", "sentence."]

and if you need it with a space, why don't you just do that? (use a loop afterwards)

var str = "This is an amazing sentence.";
var words = str.split(" ");
for (var i = 0; i < words.length - 1; i++) {
    words[i] += " ";
}
console.log(words);
//["This ", "is ", "an ", "amazing ", "sentence."]

Oh, and sleep well!


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

try this

var words = str.replace(/([ .,;]+)/g,'$1§sep§').split('§sep§');

This will

  1. insert a marker §sep§ after every chosen delimiter [ .,;]+
  2. split the string at the marked positions, thereby preserving the actual delimiters.