Limit text to specified number of words using Javascript

  • Home / Limit text to specified number of words using Javascript

Limit text to specified number of words using Javascript

Last night, a friend came to me with a problem. His text was breaking the style on his page and he needed to limit this text so as not to have a neat layout. We first of all decided to give that DIV a fixed height so that even if the text overflowed, the div will not expand and this will keep our layout neat.

Just then, we realized another issue. The DIV did not tell us where the text was going to cut. On some browsers, the text cut at a new line and some others, it cut horizontally on the text so a line was going to display only half of it. This was not neat at all and so we resorted to use Javascript to limit the number of words. This method proved to be the most efficient and worked fine on all browsers.

This is not the first time I have had such a problem and each time, I have to rethink the algorithm before writing out the code. It is really simple and takes just a few minutes though but software we are in the cheetah generation and things should be done faster so why think when someone has already done it! Just copy paste and move on to the next issue to save development time.

Besides, not all of us are programmers nor are comfortable with Javascript so this small code will help you if you have the same problem.

Here is the small and really stupid way to do this:

function limitWords(textToLimit, wordLimit)
var finalText = “”;

var text2 = textToLimit.replace(/\s+/g, ‘ ‘);

var text3 = text2.split(‘ ‘);

var numberOfWords = text3.length;

var i=0;

if(numberOfWords > wordLimit)
for(i=0; i< wordLimit; i++)
finalText = finalText+” “+ text3[i]+” “;

return finalText+”…”;
else return textToLimit;

What the function does is really simple. It take two parameters which are the text to be limited and the number of words to limit it to.

It then replaces all double spaces to single spaces and then splits the text by all spaces into an array to get each individual word. It then carries out a word count and if the number of words is less than the word limit, then there is no work to be done.
Otherwise, it creates a new string limited to the word limit and returns that.

Easy and enjoy!!!

Leave Comments