我可以问一下JavaScript中字符串对象slice()
和substr()
之间有什么区别吗?
答案 0 :(得分:34)
他们有不同的签名,.slice()
是:
string.slice(beginIndex, endIndex)
string.substr(beginIndex, length);
例如,如果我们有"1234"
并想要"23"
,那就是:
"1234".slice(1,3)
//or...
"1234".substr(1,2)
答案 1 :(得分:5)
String.slice(begin, end)
此方法会将文本从begin
剪切为end
char,例如:
alert("Hello World!".slice(1, 8)); // ello Wo
String.substr(begin, length)
此方法会将文字从begin
剪切为begin
+ length
字符,例如:
alert("Hello World!".substr(1, 8)); // ello Wor
答案 2 :(得分:2)
var str="Hello world!";
document.write(str.substring(3,7)+"<br />");
document.write(str.slice(3,7)+"<br />");
document.write(str.substr(3,7));
结果:
lo w
lo w
lo worl
答案 3 :(得分:1)
SUBSTRING()
1.如果start等于stop,则返回一个空字符串。 2.如果省略stop,则将字符提取到字符串的末尾。 3.如果开始&gt;停止,然后substring将交换这两个参数。 4.如果任一参数大于字符串的长度,则任一参数都将使用字符串的长度。 5.如果任一参数小于0或是NaN,则将其视为0。
切片()
1.如果start等于stop,则返回一个空字符串,与substring()完全相同。 2.如果省略stop,则切片将字符串提取到字符串的末尾,与substring()完全相同。 3.如果开始&gt; stop,slice()不会交换2个参数。 4.如果任一参数大于字符串的长度,则任一参数都将使用字符串的长度,与substring()完全相同。
答案 4 :(得分:0)
我认为str.slice()
和str.substr()
之间的区别是第二个参数:
.slice()
需要EndIndex,而.substr()
需要长度,如下所示:
.slice(StartIndex,EndIndex)
和.substr(StartIndex,length).