javascript Jquery:用数组中的值替换字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13755199/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 19:41:33  来源:igfitidea点击:

Jquery: Replace string with values from an array

javascriptjqueryarraysreplace

提问by Bennett

Say I have something like this:

说我有这样的事情:

var array = [cat,dog,fish];
var string = 'The cat and dog ate the fish.';

I want to clear all those values from a string

我想从字符串中清除所有这些值

var result = string.replace(array,"");

The result would end up being: The and ate the .

结果将是: The and ate the .

Right now, replace()appears to only be replacing one value from the array. How can I make it so all/multiple values from the array are replaced in the string?

现在,replace()似乎只替换数组中的一个值。我怎样才能让它在字符串中替换数组中的所有/多个值?

Thanks!

谢谢!

回答by jAndy

You either createa custom regexpor you loop over the string and replace manually.

您要么创建自定义正则表达式,要么遍历字符串并手动替换。

array.forEach(function( word ) {
    string = string.replace( new RegExp( word, 'g' ), '' );
});

or

或者

var regexp = new RegExp( array.join( '|' ), 'g' );

string = string.replace( regexp, '' );

回答by VisioN

string.replace(new RegExp(array.join("|"), "g"), "");