9

I have a HTML page which shows a Name dynamically. Now this name (FN LN) can be upto 240 charcaters. But at the UI side, I want to trim the FN/LN after about 50 characters and replace with ...

How can I do this using Javascript/jQuery

1
  • 1
    FN.substring(0, 50); will this help you... Commented Dec 8, 2011 at 6:58

4 Answers 4

18
$("#FN, #LN").each (function () {
  if ($(this).text().length > 50)
    $(this).text($(this).text().substring(0,50) + '...');
});

This should work.

Sign up to request clarification or add additional context in comments.

Comments

10

Something as simple as:

if (name.length > 50) {
    name = name.substr(0,50)+'...';
}

Comments

3
if ($('#name').text().length > 50)
{
    $('#name').text( $('#name').text().substring(0,50)+"..." );
}

But you can also use CSS for this: http://mattsnider.com/css/css-string-truncation-with-ellipsis/

1 Comment

Thanks. I did not know that myself a minute ago. Thats why I love stackoverflow ;)
3

here's a regex way to do that :

text.replace(/(^.{50}).*$/,'$1...');  

Since you've asked, if you want to jqueryfy this functionality, you can make a plugin out of it :

$.fn.trimAfter(n,replacement){
    replacement = replacement || "...";
    return this.each(function(i,el){
        $(el).text($(el).text().substring(n) + replacement);
    });
}

And use it like this :

$("#FN, #LN").trimAfter(50,'...');

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.