JavaScript break sentence by words
try this
var words = str.replace(/([ .,;]+)/g,'$1§sep§').split('§sep§');
This will
- insert a marker
§sep§
after every chosen delimiter[ .,;]+
- split the string at the marked positions, thereby preserving the actual delimiters.
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."]
If you need spaces and the dots the easiest would be.
"This is an amazing sentence.".match(/.*?[\.\s]+?/g);
the result would be
['This ','is ','an ','amazing ','sentence.']