Split String in Half By Word

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

    I first thought I had an off-by-one error, but I eventually worked through it. Here's a working example.

    Now to break down the logic used:

    var calculate = function(initialString) {
      var halfwayPoint = Math.floor(initialString.length / 2);
      var strArray = initialString.split(' ');
      // Caluclate halfway point, then break string into words
    
      var wordFlag;  // Will be split point
      var charCount = 0;
      _.each( strArray, function(word, strArrayIndex) {
        if (wordFlag) return false;
        // If we have the location, exit
    
        // If charCount is before the halfway point
        // and the end of word is after halfway point
        // Then set the flag
        // We add strArrayIndex to the word length to include spaces
        if (charCount <= halfwayPoint && 
          ((charCount + word.length + strArrayIndex) >= halfwayPoint) ) {
          wordFlag = strArrayIndex;
          return false;
        }
    
        // Increase charCount to be length at the end of this word
        charCount += (word.length);
      });
    
      if (!wordFlag) return null;
    
      // Split the word array by the flag we figured out earlier
      var lineOneArray = strArray.slice(0, (wordFlag + 1));
      var lineTwoArray = strArray.slice(wordFlag + 1);
    
    
      // We now join the word arrays into a string, stripping beginning and ending spaces.
      var stOne = (lineOneArray.join(' ')).replace(/^\s\s*/, '').replace(/\s\s*$/, '');
      var stTwo = (lineTwoArray.join(' ')).replace(/^\s\s*/, '').replace(/\s\s*$/, '');
    
      // Finally return the split strings as an array.
      return [stOne, stTwo];
    };
    

    If anyone sees holes in my logic, let me know! I'm pretty sure this works in most cases though.

    If you'd like the second string to be longer than the first, (ie have the line break before rather than after the middle word), then don't add +1 to wordFlag.

提交回复
热议问题