简体   繁体   English

如何编写一个 JS 函数从字符串中删除某些符号的数组

[英]How to write a JS function to remove the array of certain symbols from the string

Need to write a function, that takes two arguments:需要编写一个函数,它需要两个参数:

  1. the first is a string第一个是字符串
  2. the second is an array of symbols we need to exclude from the string.第二个是我们需要从字符串中排除的符号数组。

As a result it should turn out as `foo('hello world', ['o']);结果应该是`foo('hello world', ['o']); // 'hell wrld' // '地狱wrld'

Here is the example for the case if we have only one symbol to remove:如果我们只有一个要删除的符号,则示例如下:

function foo(string, array) {
  var newString = '';
  for (var i = 0; i < string.length; i++) {
    newString += string[i].replace(array, '');                      
  }
  return newString; 
}

//lad up n guns bring yur friends
console.log(foo('load up on guns bring your friends',['o'])); 

You could build a regular expression and remove the unwanted characters.您可以构建一个正则表达式并删除不需要的字符。

 function foo(string, array) { return string.replace(new RegExp(array.join('|'), 'gi'), ''); } console.log(foo('load up. on guns bring your friends.', ['o', 'i', '\\\\.']));

An approach without a regular expression.一种没有正则表达式的方法。

 function replace(string, array) { var search = new Set(array); return Array.from(string, c => search.has(c) ? '' : c).join(''); } console.log(replace('load up on guns bring your friends', ['o', 'i']));

You can use for loop to loop through all replacable elements & remove matching characters using regexmatch on string您可以使用 for 循环遍历所有可替换元素并在字符串上使用 regexmatch 删除匹配的字符

 function foo(string, array) { for(const a of array){ let pattern = new RegExp(a, 'g'); string = string.replace(pattern, ''); } return string; } console.log(foo('load up on guns bring your friends',['o','i'])); //lad up n guns bring yur friends

you can do this by simply using regex like given below你可以通过简单地使用下面给出的正则表达式来做到这一点

 function foo(str,arr) { var regExp = new RegExp('['+arr.join(',')+']+','g'); console.log(str.replace(regExp, "")); } foo("hello world",['o'])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM