Reputation: 2723
I'm trying to limit a variable. If it contains more than 300 letters, it should be trimmed, so that there are ONLY 300. Is there any way to do this in jQuery?
Upvotes: 0
Views: 1345
Reputation: 793
Javascript has two native methods for this...
string.substring(from, to)
variable_name = variable_name.substring(0,300)
and
string.substr(start,length)
variable_name = variable_name.substr(0,300)
both of them should do the trick.
Edit: as @freakish suggested
string.slice(beginslice, endSlice)
variable_name = variable_name.slice(0,300)
Note: substring
and slice
are roughly the same, except slice
can accept negative indices (relative to the end of the string), where as substring
can't. Also, substr
takes length as its 2nd parameter.
Upvotes: 3
Reputation: 4057
No need for jQuery - just using substring in JS should do the trick
var originalString = 'This content is more than 300 characters... This content is more than 300 characters... This content is more than 300 characters... This content is more than 300 characters... This content is more than 300 characters... This content is more than 300 characters... This content is more than 300 characters... This content is more than 300 characters... ';
document.write(originalString.substring(0, 300));
Upvotes: 1
Reputation: 1964
// Assume really_long_string is over 300 characters long
var really_long_string = "abcdefg..."
// Your new string, truncated to fit your desired length
var shortened_string = really_long_string.substring(0, 300)
Upvotes: 1