Search code examples
javascriptstringchop

Why is my word chopped in half?


I am trying to chop text to a fixed length, but I don't want to chop words at half, so I need to do something like this:

function fixedLength(str, len, bol) {
    var i, l = str.length, left = 0, right = l - 1, rtn, tmp;

    tmp = str.charAt(len);

    if (bol || tmp === " " || tmp === "") {
        rtn = str.substr(0, len);
    } else {
        tmp = len - 1;

        for (i = tmp; i > -1; i--) {
            if (str.charAt(i) === " ") {
                left = i;
                break;
            }
        }

        for (i = tmp; i < l; i++) {
            if (str.charAt(i) === " ") {
                right = i;
                break;
            }
        }

        rtn = str.substr(0, ((Math.abs(left - tmp) <= Math.abs(right - tmp)) ? left : right));
    }

    return rtn + "...";
}

But when I use it with this:

var str = "the quick brown fox jumped over the lazy dog";

for (var i = 0; i < 45; i++) {
    document.write("i:" + i + " - " + fixedLength(str, i) + "<br>");
}

Everyone seems to work correctly except in this line "i:43 - the quick brown fox jumped over the lazy do...", the word "dog" is chopped in half (Demo)

I can't find the flaw, every time I change something, I add a new bugs


Solution

  • Didn't check your code, but you could write your code more simple:

    function fixedLength(str, len, bol) {
        while(!bol && str[len] && str[len] !== ' ') {
          len--;
        }
        return str.substr(0, len) + '...';
    }
    

    And the demo.