简体   繁体   English

替换字符串中所有出现的内容,将数组作为参数

[英]Replace all occurrences in string giving an array as a parameter

Is there a way to replace all occurrences in string giving an array as a parameter in replace() method. 有没有一种方法可以替换字符串中所有出现的内容,从而在replace()方法中将数组作为参数。

For example: 例如:

Having this string: "ABCDEFG" 具有以下字符串: "ABCDEFG"

And having this array: ['A','D','F'] 并具有以下数组: ['A','D','F']

It is possible to replace the same letters in the string with something else? 可以用其他东西替换字符串中的相同字母吗? Something like: 就像是:

"ABCDEFG".replace(['A','D','F'], '')

So the final result be: "BCEG" 所以最终结果是: "BCEG"

You can loop through your array: 您可以遍历数组:

 var str = "ABCDEFG"; ['A','D','F'].forEach(c => str = str.replace(c, '*')) console.log(str); 

No. You will have to iterate through your array of replacements, calling replace() for every individual item in the array I'm afraid. 否。您将不得不遍历替换数组,恐怕要为数组中的每个项目调用replace() Alternatively, you could try to formulate your array of individual strings as a regular expression, eg 另外,您可以尝试将各个字符串数组公式化为正则表达式,例如

"ABCDEFG".replace(/(A|D|F)/g, '')

Please note, though, that depending on your array and the length of strings in it, this may be considerably less efficient than a number of replace calls. 但是请注意,根据您的数组及其中字符串的长度,其效率可能比许多替换调用的效率低得多。

的种类:

 "ABCDEFG".replace(new RegExp(['A','D','F'].join("|")), '')

There is actually a way to do this from an Array. 实际上,可以通过数组来执行此操作。

You'll need to create a RegEx dynamically : 您需要动态创建一个RegEx:

 let arr = ['A','D','F']; let expression = arr.join('|'); let rx = new RegExp(expression, 'g'); console.log("ABCDEFG".replace(rx,'')); 

If you want an array as input: 如果要使用数组作为输入:

'ABCDEF'.replace(new RegExp(['A','D','F'].join('|'), 'g'), '')

By using the 'g' flag, it will replace all occurrences of 'A', 'D' or 'F' in the string. 通过使用“ g”标志,它将替换字符串中所有出现的“ A”,“ D”或“ F”。

You could also do this in a simpler way: 您还可以通过一种更简单的方式执行此操作:

'ABCDEF'.replace(/A|D|F/g, '')

Here's a general function that uses regex similar to the other answers, but allows you to pass in whatever replacement string you like: 这是一个与其他答案类似的使用regex的常规函数​​,但允许您传入任何喜欢的替换字符串:

 const str = 'ABCDEFG'; const arr = ['A', 'D', 'F']; function replace(str, arr, r) { const regex = new RegExp(arr.join('|'), 'g'); return str.replace(regex, p => r); } console.log(replace(str, arr, '')); console.log(replace(str, arr, 'bob')); 

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

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