Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript break sentence by words

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.

like image 456
THE AMAZING Avatar asked Aug 27 '13 18:08

THE AMAZING


People also ask

How do you split a sentence with the word JavaScript?

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.

What does split do in JavaScript?

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.

How do you split a sentence into an 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.


2 Answers

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."] 
like image 179
Isaac Avatar answered Oct 05 '22 23:10

Isaac


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!

like image 20
h2ooooooo Avatar answered Oct 05 '22 22:10

h2ooooooo