Christian Heilmann

Shortening strings to a fixed length in JavaScript

Friday, August 25th, 2006 at 5:11 pm

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.

[tags]string concatenation webdevtrick[/tags]

Share on Mastodon (needs instance)

Share on BlueSky

Newsletter

Check out the Dev Digest Newsletter I write every week for WeAreDevelopers. Latest issues:

Word is Doomed, Flawed LLM benchmarks, hard sorting and CSS mistakes Spot LLM benchmark flaws, learn why sorting is hard, how to run Doom in Word and how to say "no" like a manager.
30 years of JS, Browser AI, how attackers use GenAI, whistling code Learn how to use AI in your browser and not on the cloud, why AI makes different mistakes than humans and go and whistle up some code!
197: Dunning-Kruger steroids, state of cloud security, puppies>beer
196: AI killed devops, what now? LLM Political bias & AI security Learn how AI killed DevOps, create long tasks in JS, why 1 in 5 security breaches are AI generated code & play "The Scope Creep"
195: End of likes, JS Zoo and Tim Berners-Lee doesn't see AI vs Web Meta kills like buttons, Tim-Berners-Lee thinks AI won't kill the web, GitHub is ending toasts and the worst selling Microsoft product.

My other work: