How do I only display part of a string using css

DannyD picture DannyD · Mar 14, 2013 · Viewed 22.3k times · Source

I want to be able to display a string of characters up to 10 characters. If the string goes over 10 characters, I'd like to append '...' to the end.

For example, if I have the string:

'helloworldmynameisryan'

I want it to be displayed like so:

'helloworld...'

I'm just displaying my string in a div like this:

<div>DisplayMessage</div>

Is there a class that I could create that would only apply if the string were over 10 char?

Answer

Sushant Sudarshan picture Sushant Sudarshan · Mar 14, 2013

Unfortunately there isn't a good cross browser way to do this using only CSS. 'text-overflow' relies on the width of the string, and not the length of string as you need.

You can use the .length property of strings in javascript to achieve this

function ellipsify (str) {
    if (str.length > 10) {
        return (str.substring(0, 10) + "...");
    }
    else {
        return str;
    }
}

Hope this helps.