【前端笔试】JS中字符串的截取

来源:互联网 发布:阿拉曼战役 知乎 编辑:程序博客网 时间:2024/06/09 21:10

字符串对象有三个方法都可以用来截取,分别是
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,也就是说会返回整个字符串。