我处在一种情况下,我想取一个字符串并将其分成两半,尊重单词,以便此字符串不会分裂成此str 此处,而不是将其分成此字符串 此处。
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.
示例:
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);演示: jsfiddle/7RNBu/
(此代码假设中间两侧实际上有空格。你会还要在之前添加对的检查,在之后添加 -1 的检查。 )
(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; }这是一个小提琴,您可以在其中编辑文本并立即查看结果: jsfiddle/Guffa/7RNBu/11/
Here is a fiddle where you can edit the text and see the result immediately: jsfiddle/Guffa/7RNBu/11/
更多推荐
用字分割一半的字符串
发布评论