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

时间:2022-09-25 08:15:14

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 .

结果将最终成为:并且吃了。

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!

谢谢!

2 个解决方案

#1


10  

You either create a custom regexp or 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, '' );

#2


2  

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

#1


10  

You either create a custom regexp or 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, '' );

#2


2  

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