Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split String in Half By Word

Tags:

javascript

I'm in a situation where I'd like to take a string and split it in half, respecting words so that this string here doesn't get split into this str ing here, rather it would be split into this string here.

I figure a starting step would to be to split the string into an array based on spaces, then calculate length based on those pieces, but in my attempts longer strings end up being split up incorrectly.

like image 729
AlbertEngelB Avatar asked Aug 06 '13 18:08

AlbertEngelB


1 Answers

Look for the first space before and after the middle, and pick the one closest to the middle.

Example:

var s = "This is a long string";

var middle = Math.floor(s.length / 2);
var before = s.lastIndexOf(' ', middle);
var after = s.indexOf(' ', middle + 1);

if (middle - before < after - middle) {
    middle = before;
} else {
    middle = after;
}

var s1 = s.substr(0, middle);
var s2 = s.substr(middle + 1);

Demo: http://jsfiddle.net/7RNBu/

(This code assumes that there actually are spaces on both sides of the middle. You would also add checks for before and after being -1.)

Edit:

The check that I talked about in the node would be done correctly like this:

if (before == -1 || (after != -1 && middle - before >= after - middle)) {
    middle = after;
} else {
    middle = before;
}

Here is a fiddle where you can edit the text and see the result immediately: http://jsfiddle.net/Guffa/7RNBu/11/

like image 184
Guffa Avatar answered Oct 12 '22 04:10

Guffa