Apr, 16
2009

Quickly Trim Text with Regular Expressions and jQuery

I ran into an issue ( a while back but finally had time to address it ) where we had lines of text that we could trim down to fit an HTML container. If the text was longer that 37 characters, we stripped off the end and replaced it with ‘…’. The problem with doing this strictly on a character count basis was that the break would usually be mid-word and with some words like, assign, that would could be bad.

A simple way to fix address this is to use regular expressions. Specifically, this regular expression: ^(.){1,37}\b

My solution was to use javascript and css to replace the text on the fly. Applying the ‘white-space:nowrap’ style to the text element allows me to keep everything on one line. Overflow:hidden hides the text that would flow out of the block. This helps me keep a minimum amount of text visible until the javascript function applies the fix. Also, I’m using in-line javascript (big no-no) but it does the job fast.

This is the script:

function trimText(element)
{
     var list = $(element);
     var regToShow = new RegExp(/^(.){1,37}\b/);
     list.each(function(){
          var toShow = $(this).text().match(regToShow);
          $(this).text(toShow[0]+'...');
     });
}
trimText(Selector);

Basically, what I’m doing here is applying the regular expression to the called-in-class’ text. If you know about regular expressions or want to know more about them, check out RegExr. It’s an online and downloadable (Adobe Air) tool for regular expressions testing and design.  You can also put in a conditional statement if you don’t to add the ‘…’ at the end unless you are actually trimming the line.

if($(this).text()!=toShow[0])
     $(this).text(toShow[0]+'...');

This just checks to see if the final text is the same as the original text (i.e. no trimming) and if so, do not add ‘…’.

It’s quick and dirty but it works. It would work better if you apply the Regular Expression in the code BEFORE the text gets rendered, but sometimes, that’s not a viable option.

Leave a Reply