0

I want to trim a string down to a particular pixel width so that it can properly fit in a container. It will be similar to substring, except that I am trimming based on pixel width as opposed to number of characters. is there a built in function for this?

4
  • What happens when the pixel width occurs within the space of a letter (say half-way through an 'm')? Do you expand the string to include the full 'm', or round it down to omit the 'm'? Oh, and no, there isn't a built in JS function for this, though CSS does it quite easily. Commented Jul 27, 2011 at 17:34
  • 5
    Just out of curiosity, what's your application for this? You could easily just let the string overflow it's container but use overflow: hidden. Commented Jul 27, 2011 at 17:34
  • @David Thomas: I will omit the 'm' in that case. Commented Jul 27, 2011 at 17:36
  • @CrazyJugglerDrummer: I am aware of the overflow: hidden property. however, it is not sufficient in this case because I am adding ellipsis to an overflowing word and text-overflow: ellipsis is not supported in mozilla Commented Jul 27, 2011 at 17:37

3 Answers 3

3

Maybe this is what you're looking for:
jQuery Text Overflow plugin

Lg
warappa

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

Comments

0

You can do it via css: text-overflow: clip;

Note: This is not supported in FF < 7. Every other browser including IE6 supports it.

Try this:

function trimByPixel(str, width) {
    var spn = $('<span style="visibility:hidden"></span>').text(str).appendTo('body');
    var txt = str;
    while (spn.width() > width) { txt = txt.slice(0, -1); spn.text(txt + "..."); }
    return txt;
}

3 Comments

I know. that is not what I'm after.
FF < 7? I just upgraded to 5.0.1, so I don't think there's even a beta for Firefox 6 yet... :D
:) You can get FF8 alpha release if you go to nightly builds: nightly.mozilla.org
0

CSS might be the easiest/best option, especially if you're trying to keep text confined to an area. Check out both word-wrap and text-overflow, as they might be v

1 Comment

I already know about those and they are not what I'm looking for.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.