JS如何去除指定字符串或数组元素

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/cristina_song/article/details/83149134

去除指定字符串

1.去掉字符串一次(最前面的)

使用replace函数替换

var str="hello world!";
str=str.replace("l","");//输出:"helo world!"

2.去掉相同字符串(所有的)

使用字符串分割函数再聚合

var str="hello world!"
var items=str.split("o")//item为["hell", " w", "rld!"],w前面有个空格
console.log(items.join(""));//输出:hell wrld!

去除指定数组元素

删掉一个2(最前面的)

var arr = [1,2,2,1];
for(let i=0;i<arr.length;i++){
    if(arr[i]==2){
      arr.splice(i,1);
      break;//该行代码变成i--,则移除所有2
    }
}
console.log(arr);//[1, 2, 1]

猜你喜欢

转载自blog.csdn.net/cristina_song/article/details/83149134