Split String in Half By Word

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

    This will split your string based on word count (not character count, so the exact length of each half could be quite different, depending on the placement of long & short words).

    var s = "This is a string of filler text";
    
    var pieces = s.split(" "),
        firstHalfLength = Math.round(pieces.length/2),
        str1 = "",
        str2 = "";
    
    for (var i = 0; i < firstHalfLength; i++){
        str1 += (i!=0?" ":"") + pieces[i];
    }
    for (var i = firstHalfLength; i < pieces.length; i++){
        str2 += (i!=firstHalfLength?" ":"") + pieces[i];
    }
    
    document.write(s);
    document.write("
    "+str1); document.write("
    "+str2); // Output This is a string of filler text This is a string of filler text

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

提交回复
热议问题