目录
一、slice方法
slice方法用于删除指定位置范围的字符
代码:
let str = "tomato";
// str.slice(index)用法
let newStr1 = str.slice(0); // index等于0时,不删除字符串中任何字符
console.log('newStr1 :'+newStr1);
let newStr2 = str.slice(3); // index等于n时,删除字符串中前n个字符
console.log('newStr2 :'+newStr2);
// str.slice(0,index)+str.slice(index+m)用法
let newStr3 = str.slice(0,2)+str.slice(4); // 从第index+1个删除到第index+m个字符
console.log('newStr3 :'+newStr3);
运行结果:
二、replace方法
replace方法用于替换字符串中所有指定字符为其他字符
代码:
let str = "ishift";
//str.replace('m','n')用法
let newStr1 = str.replace('f',''); // n为空时,可达到删除字符串中m的效果
console.log('newStr1 : '+newStr1);
let newStr2 = str.replace('i',''); // 字符串中i有多个时,默认删除字符串中第一个i
console.log('newStr2 : '+newStr2);