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.
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
.)
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With