JavaScript break sentence by words

javascript, jquery

Solution

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!

Problem

What's a good strategy to get full words into an array with its succeeding character. Example. This is an amazing sentence. ``` Array( [0] => This [1] => is [2] => an [3] => amazing [4] => sentence. ) ``` Elements 0 - 3 would have a succeeding space, as a period succeeds the 4th element. I need you to split these by spacing character, Then once width of element with injected array elements reaches X, Break into a new line. Please, gawd don't give tons of code. I prefer to write my own just tell me how you would do it.

Original source

Related problems