截取数组用slice()方法,截取字符串同样可以使用slice()
var srt="hello world";
//截取从索引为7的开始,到索引为9结束,索引10不截取
console.log(str.slice(7,10));//输出:orl,如果后面的参数不设置,就会截取索引7以后所有内容
console.log(str.slice(-7,-2));//输出:o wor,如果参数是负数,那就是长度+负数
substring()方法,语法功能和slice()基本一样,区别在于,参数是负数的时候,自动转换成0:
var srt="hello world";
//截取从索引为2的开始,到索引为4结束,索引4不截取
console.log(str.substring(1,4));//输出:ell,
console.log(str.sunstring(-5,5));//输出:hello,负数为索引0开始
console.log(str.sunstring(-1,-5));//输出:空
console.log(str.sunstring(2,-5));//输出:he,自动转换索引(0,2)
substr()方法
var srt="hello world";
//截取从索引为6的开始,一共截取3个字符串
console.log(str.substr(6,3));//输出:wor
console.log(str.sunstr(-5,4));//输出:worl,总长度为11,11-5=6,总共截取4个字符
console.log(str.sunstr(1,-5));//输出:空,截取字符长度为0