我正在尝试限制变量。如果它包含超过300个字母,则应该进行修剪,以便只有300个。有没有办法在jQuery中执行此操作?
答案 0 :(得分:6)
只需pure JavaScript:
myVar = myVar.substring(0, 300);
答案 1 :(得分: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)
注意:substring
和slice
大致相同,只有slice
可以接受否定索引(相对于字符串的结尾),而substring
可以'吨。此外,substr
将长度作为其第二个参数。
答案 2 :(得分: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)
答案 3 :(得分: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));