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.
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.
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;
if(numberOfWords > wordLimit)
for(i=0; i< wordLimit; i++)
finalText = finalText+” “+ text3[i]+” “;
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!!!