关于javascript:JS截取字符串

26次阅读

共计 1080 个字符,预计需要花费 3 分钟才能阅读完成。

1、应用 slice(start,end)截取

其中 start 必传,end 非必传,指定的开始和完结地位,提取字符串的某个局部,并以新的字符串返回被提取的局部
例子:
var str = “0123456789”;
console.log(“ 原始字符串:”, str);
console.log(“ 从索引为 3 的字符起始终到完结:”, str.slice(3)); //3456789
console.log(“ 从倒数第 3 个字符起始终到完结:”, str.slice(-3)); //789
console.log(“ 从开始始终到索引为 5 的前一个字符:”, str.slice(0,5)); //01234
console.log(“ 从开始始终到倒数第 3 个字符的前一个字符:”, str.slice(0,-3)); //0123456

2、应用 substring(start,end)截取

其中 start 必传,end 非必传,办法用于提取字符串中介于两个指定下标之间的字符,内容是从 start 处到 stop-1 处的所有字符,其长度为 stop 减 start
例子:
var str = “0123456789”;
console.log(“ 原始字符串:”, str);
console.log(“ 从索引为 3 的字符起始终到完结:”, str.substring(3)); //3456789
console.log(“ 从索引为 20 的字符起始终到完结:”, str.substring(20)); //
console.log(“ 从索引为 3 的字符起到索引为 5 的前一个字符完结:”, str.substring(3,5)); //34
console.log(“start 比 end 大会主动替换,后果同上:”, str.substring(5,3)); //34
console.log(“ 从索引为 3 的字符起到索引为 20 的前一个字符完结:”, str.substring(3,20)); //3456789

3、应用 substr(start,length) 截取

其中 start 必传,length 非必传,length 示意返回的子字符串中应包含的字符个数,
例子:
var str = “0123456789”;
console.log(“ 原始字符串:”, str);
console.log(“ 从索引为 3 的字符起始终到完结:”, str.substr(3)); //3456789
console.log(“ 从索引为 20 的字符起始终到完结:”, str.substr(20)); //
console.log(“ 从索引为 3 的字符起截取长度为 5 的字符串:”, str.substr(3,5)); //34567

正文完
 0