Split String in Half By Word

前端 未结 5 945
走了就别回头了
走了就别回头了 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:10

    I wanted to leave this as a comment but do not have enough rep points. The top solution right now fails pretty easily because it does not check for "-1" when using the indexOf method. See this fiddle:

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

    var s = "This is a long strinjjjjjjjjjjjjjjjjg";
    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);
    

提交回复
热议问题