Tristan Kirkpatrick
Tristan Kirkpatrick

Reputation: 155

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.

Upvotes: 10

Views: 4592

Answers (2)

Ωmega
Ωmega

Reputation: 43673

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.

Upvotes: 11

dfsq
dfsq

Reputation: 193261

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);

Upvotes: 8

Related Questions