pangi
pangi

Reputation: 2723

Limit variable length

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

Answers (4)

Faisal Sayed
Faisal Sayed

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

geedubb
geedubb

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

alexpls
alexpls

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

VisioN
VisioN

Reputation: 145458

Just pure JavaScript:

myVar = myVar.substring(0, 300);

Upvotes: 6

Related Questions