Solomon Solomon - 1 month ago 16
Javascript Question

How do I split a string, breaking at a limit n length?

I have this string

It's important to remember that this function does NOT replace newlines
with <br> tags. Rather, it inserts a <br> tag before each newline, but
it still preserves the newlines themselves! This caused problems for me
regarding a function I was writing -- I forgot the newlines were still
being preserved.


Using JavaScript, what is the fastest way to parse this into

var string1 = "It's important to remember that this function does ...";


This means, I want limit string that has n length and in the end it has '...'.

Help me.

Answer

If you don't want to cut words in the middle:

function shortener(s, n){

    var ret = "";
    if(s.charAt(n) !== " "){
        var fullWords = s.substring(0, n).split(" ").length - 1;
        ret = s.split(" ").splice(0, fullWords).join(" ");
    }
    else{
        ret = s.substring(0, n);
    }
    return ret + " ...";
}
var s = "It's important to remember that this function does NOT replace newlines  with <br> tags. Rather, it inserts a <br> tag before each newline, but  it still preserves the newlines themselves! This caused problems for me regarding a function I was writing -- I forgot the newlines were still being preserved. ";

console.log(shortener(s, 16));
console.log(shortener(s, 4));
console.log(shortener(s, 80));

Output:

  • It's important ...
  • It's ...
  • It's important to remember that this function does NOT replace newlines with ...