Set character limit to display in a paragraph
I am pulling from a JSON feed and I just want 开发者_运维问答to display a maximum of 10 characters of the string and then do a ... afterwards. How do I do that with JQuery?
You can use CSS to set up an ellipsis:
.myparagraph {
white-space: nowrap;
width: 10em;
overflow: hidden;
text-overflow: ellipsis;
}
Then there's no need for any jQuery or other coding.
References:
- http://www.quirksmode.org/css/textoverflow.html
- http://www.electrictoolbox.com/ellipsis-html-css/
(note that first link - Quirksmode.org is an excellent resource generally for CSS and Javascript stuff)
I haven't checked this for off by one errors, so you might have to adjust for poor indexing.
var txt = SomeStringFromFeed;
if(txt.length > 10)
{
txt = txt.substr(0,10) + "...";
}
return txt;
you don't need jquery, JS can do that:
string.substr(start,length) start The index where to start the extraction. First character is at index 0 length The number of characters to extract. If omitted, it extracts the rest of the string
I don't believe the CSS solution mentioned by @spudley is cross browser (no firefox support). Assuming you care about that of course. The first link he provides even states the limited support in the top right corner of the page.
Now, having said that I have a nice little function that may be overkill for what you need, but I have found I use this regularly in similar situations. The code below has been commented, but what this does is it only inserts an ellipsis after the last full word based on the set limit.
So you can return "The dog jumps..." instead of "The dog Jumps ove..."
// ==============================================================================================
// Truncate a string to the given length, breaking at word boundaries and adding an elipsis
// @param str - String to be truncated
// @param limit - integer Max length of the string
// @returns a string
// ==============================================================================================
function truncate(str, limit) {
var chars;
var i;
// check if what was passed as a string is actually a string
if ( typeof(str) != 'string') {
return '';
}
// create an array of the chars in the string
chars = str.split('');
// if the length is greater than the set limit, process for truncating
if (chars.length > limit) {
// while the char count is greater than the limit,
for (i = chars.length - 1; i > -1; --i) {
// if char count is still greater, redefine the array size to the value of i
if (i > limit) {
chars.length = i;
}
// if char count is less than the limit keep going until you hit a space
// and redefine the array size to the value of i
else if (' ' === chars[i]) {
chars.length = i;
break;
}
}
// add elipsis to the end of the array
chars.push('...');
}
// return the array as a string
return chars.join('');
}
Truncate a string with JavaScript
精彩评论