在字符串中创建新字符串的方法我们今天介绍三种,slice、substring、substr
我们先介绍一下它们三个的区别
str.slice(start, end), start<= 字符 < end , 如果是负数就是从后向前找;
str.substring(start, end),当参数为正数时start<= 字符 < end ,当参数为负数时,对应索引为0(无论是第一个参数还是第二个参数)小的数为start, 大的数为end;
str.substr(index,howmany),第一个数为其实位置的下标,第二个数为要截取几个;
下面我们用实际的例子来看看
var str = "hello world";
console.log(str.slice(6)); //"world"
console.log(str.substring(6)); //"world"
console.log(str.substr(6)); //"world"
当有一个参数的时候是不是三个都一样
var str = "hello world";
console.log(str.slice(2,7)); //"llo w"
console.log(str.substring(2,7)); //"llo w"
console.log(str.substr(2,7)); //"llo worl"
同样是(2,7)substr是不是就不一样了呢,因为它的7是往后截取7个;
var str = "hello world";
console.log(str.slice(-3)); //"rld"
console.log(str.substring(-3); //"hello world" 此方法的参数是负数都转换为0
console.log(str.substr(-3)); //"rld"
console.log(str.slice(3,-4)); //"lo w"
console.log(str.substring(3,-4)); //"hel" 负数对应索引为0;小的数为start, 大的数为end;所以它其实就变成了str.substring(0,3);
console.log(str.substr(3,-4)); //""(空字符串)
看完例子是不是清晰了很多!!!