Search code examples
javascriptregexfor-looptruncate

cut text after 15 full words javascript


I need to cut some text after 15 words in js, I've tried to do it but only seem to find solutions that work based around certain amount of characters and not full words

function shorten(str, maxLen, separator = ' ') {
    if (str.length <= maxLen) return str;
    return str.substr(0, str.lastIndexOf(separator, maxLen));
}

example of solution


Solution

  • You can split, truncate and then join

    function shorten(str, maxLen, separator = ' ') {
        if (str.length <= maxLen) return str;
        return str.split(separator).splice(0, maxLen).join(separator);
    }
    

    In the case if you can have multiple spaces between words, then you can use regex to remove those spaces and then trim to remove spaces in beginning and end.

    function shorten(str, maxLen) {
        if (str.length <= maxLen) return str;
        const trimmed_str = str.replace(/ {1,}/g," ").trim();
        return trimmed_str.split(' ').splice(0, maxLen).join(' ');
    }