Split string to two, will have almost same length

前端 未结 3 1273
迷失自我
迷失自我 2021-01-28 20:58

I have string: \"This is a sample string\", and I need to split it to 2 strings, without break the words, and that the two strings will have the closest length, so the result wi

3条回答
  •  無奈伤痛
    2021-01-28 21:25

    You can try a splitter like

    function split(str) {
      var len = str.length,
        mid = Math.floor(len / 2);
    
      var left = mid - str.substring(0, mid).lastIndexOf(' '),
        right = str.indexOf(' ', mid) - mid;
    
      var ind = mid + (left < right ? -left : right);
    
      return [str.substr(0, ind),
        str2 = str.substr(ind)
      ];
    }
    
    var parts = split("123-456 3-5-asldfkjas kdfasdfasd fjas");
    snippet.log(parts[0]);
    snippet.log(parts[1]);
    
    

提交回复
热议问题