Split text / line in near space in Javascript

I'm really trying to split the text into the nearest line with the 47th character. How it's done?

var fulltext = document.getElementById("text").value; var a = fulltext.slice(0, 47); console.log(a); var b = fulltext.slice(47, 47*2); console.log(b); var c = fulltext.slice(94, 47*3); console.log(c); 

Here is the JS script - http://jsfiddle.net/f5n326gy/5/

Thanks.

+7
javascript jquery string split
source share
2 answers

If you are only interested in the first part, use

 var a = fulltext.match(/^.{47}\w*/) 

See the demo (fiddle) here .


If you want to split the entire string into several substrings, use

 var a = fulltext.match(/.{47}\w*|.*/g); 

See demo (violin) here .

... and if you want substrings not to start with a word delimiter (like a space or a comma) and prefer to include it with the previous match, use

 var a = fulltext.match(/.{47}\w*\W*|.*/g); 

See demo (violin) here .

+6
source share

You can find the next word boundary using indexOf with the second fromIndex parameter. After that, you can use slice to get either the left side or the right.

 var fulltext = "The slice() method selects the elements starting at the given start argument, and ends at, but does not include, the given end argument."; var before = fulltext.slice(0, fulltext.indexOf(' ', 47)); var after = fulltext.slice(fulltext.indexOf(' ', 47)); alert(before); alert(after); 
+4
source share

All Articles