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.
The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.
split() The split() method takes a pattern and divides a String into an ordered list of substrings by searching for the pattern, puts these substrings into an array, and returns the array.
Just use the split() method to convert sentences into an array of words in JavaScript. You have to use a separator which uses to indicate where each split should occur. We will use a space separator, you can use a comma or another.
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."]
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With