Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split text/string at closest space in Javascript

I'm really struggling how to split the text at the closest string to the 47th character. How is this 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 a JS Fiddle - http://jsfiddle.net/f5n326gy/5/

Thanks.

like image 281
Tristan Kirkpatrick Avatar asked Jan 03 '15 19:01

Tristan Kirkpatrick


People also ask

How do I split a space in JavaScript?

To split a string keeping the whitespace, call the split() method passing it the following regular expression - /(\s+)/ . The regular expression uses a capturing group to preserve the whitespace when splitting the string.

Can you split a string in 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.

How do I split a paragraph in JavaScript?

You could just use split() method and split it by \n\n . \n Means new line, on your text, there is 2 new line, hence we use \n\n .

Which JavaScript method is used to break a string on a character or whitespace?

JavaScript String split() Method. JavaScript str. split() method is used to split the given string into an array of strings by separating it into substrings using a specified separator provided in the argument. separator: It is used to specify the character, or the regular expression, to use for splitting the string.


2 Answers

If you are interested in just the first part, then use

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

See demo (fiddle) here.


If you want to split the entire string to multiple substrings, then use

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

See demo (fiddle) here.

...and if you wish substrings do not start with the word separator (such as space or comma) and prefer to include it with the previous match, then use

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

See demo (fiddle) here.

like image 181
Ωmega Avatar answered Sep 20 '22 20:09

Ωmega


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

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);
like image 38
dfsq Avatar answered Sep 21 '22 20:09

dfsq