Split String in Half By Word

前端 未结 5 976
走了就别回头了
走了就别回头了 2021-01-13 00:45

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

5条回答
  •  我在风中等你
    2021-01-13 01:27

    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/

提交回复
热议问题