0

我试图限制一个变量。如果它包含超过 300 个字母,则应将其修剪,以便只有 300 个。在 jQuery 中有没有办法做到这一点?

4

4 回答 4

6

只是JavaScript:

myVar = myVar.substring(0, 300);
于 2012-10-24T09:37:36.520 回答
3

Javascript 有两种本机方法...

string.substring(from, to)

variable_name = variable_name.substring(0,300)

string.substr(start,length) 

variable_name = variable_name.substr(0,300)

他们俩都应该做到这一点。

编辑:正如@freakish 建议的那样

string.slice(beginslice, endSlice)

variable_name = variable_name.slice(0,300)

注意:substringandslice大致相同,除了slice可以接受负索引(相对于字符串的末尾),而 assubstring不能。此外,substr将长度作为其第二个参数。

于 2012-10-24T09:41:51.880 回答
1
// 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)
于 2012-10-24T09:39:30.837 回答
1

不需要 jQuery - 只需在 JS 中使用子字符串就可以了

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));
于 2012-10-24T09:43:20.310 回答