Shortening strings to a fixed length in JavaScript

I have this function I’ve used for quite a long time to shorten a string to a fixed amount of characters without breaking in between words:

function constrain(str,n){ 
  var words = str.split(' '); 
  var resultstr = ''; 
  for(var i = 0; i < words.length; i++ ){ 
    if((resultstr + words[i] + ‘ ‘).length>=n){ 
      resultstr += ‘…’; 
      break; 
    }  
    resultstr += words[i] + ‘ ‘; 
  } 
  return resultstr; 
}

ately that it can get really slow with massive strings in Internet Explorer. This is a well-known issue and the solution is to use arrays instead of concatenating strings.

This made me realise how convoluted the above example is and that it is much easier to do the same with an array:

function constrain(str,n){ 
  if(str.length > n){  
    var s = str.substr(0, n);
    var words = s.split(' '); 
    words[words.length-1] = ”;
    str = words.join(’ ‘) + ‘…’
  }
return str;
}

You send a string and the amount of characters wanted as parameters and the function returns the string with the right lenght followed by a “…”.

Another way to work around the MSIE issue of slow concatenation is to use thea string builder.

2 Responses to “Shortening strings to a fixed length in JavaScript”

  1. Steve Webster Says:

    You can also do this with a regular expression and the String.replace method in a singe line of code:

    str.replace(new RegExp(”^(.{0,” + n + “}\\b).*”), “$1″);

    The benefit of using a regular expression is that you aren’t just limited to spaces separating words. The above regex will work with any character that the regular expression engine considers to be the end of a word (i.e. punctuation (other than hyphen), whitespace, etc)

  2. max Says:

    thanks for sharing!

Leave a Reply

Wait till I come! is the blog of , a developer evangelist living and working in London, England. Download vcard.

Feed me, Seymour: Entries (RSS) and Comments (RSS).