字符串对象有三个方法都可以用来截取,分别是
slice,substr和substring;
当有两个参数时
slice和substring接收的是起始位置和结束位置(start+end不包括结束位置),而substr接收的则是起始位置和所要返回的字符串长度(start+length)。
var test = ‘hello world’;
test.slice(4,7); //o w
test.substring(4,7); //o w
test.substr(4,7); //o world
如果end小于start怎么办,substring会自动调换位置,而slice不会,并返回空字符串!
当只有一个参数时
var test = ‘hello world’;
test.slice(4); //o world
test.substring(4); //o world
test.substr(4); //o world
代表从start一直截取到字符串尾部。
当出现负数时
var test = ‘hello world’;
test.slice(-4); //orld
test.substring(-4); //hello world
test.substr(-4); //orld
slice和substr会截取倒数n个,要注意的是substring会将负数当做0,也就是说会返回整个字符串。

本文详细介绍了JavaScript中三种常用的字符串截取方法:slice、substr和substring。解释了这些方法的不同用法,包括如何指定开始位置、结束位置以及长度等参数,并通过示例展示了在实际编程中的应用。
1万+

被折叠的 条评论
为什么被折叠?



