views:

88

answers:

4

i am querying text from a DB. if the text ends to be too long, I want to be able to wrap the text after, say, 400 characters and display a "..." at the end. how can it be done?

A: 

In MySQL it's:

SELECT (CASE WHEN CHAR_LENGTH(some_column) > 400 THEN CONCAT(SUBSTR(some_column, 1, 400), '...') ELSE some_column END) FROM some_table

Fill in your own column to be truncated and table, but that's the gist of it.

Sheep Slapper
+1  A: 

When you have the text in a javascript string:

newText = text.length > 400 ? (text.slice(0, 400) + ' ...'):text;
Mic
+4  A: 

I would suggest you don't do it in your query. You are probably rendering in a proportional font which means 400 characters is never the same size. "..." with a lot of white-space behind it is kinda awkward.

You can query the entire field and cut off using CSS (with limited browser support) with:

overflow: hidden;
text-overflow: ellipsis;
Tomas
A: 

You can add o-text-overflow to Tomas's solution to extend support to Opera.

sscirrus