Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery: Replace string with values from an array

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?

Thanks!

like image 283
Bennett Avatar asked Dec 07 '12 00:12

Bennett


2 Answers

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, '' );
like image 199
jAndy Avatar answered Nov 19 '22 20:11

jAndy


string.replace(new RegExp(array.join("|"), "g"), "");
like image 2
VisioN Avatar answered Nov 19 '22 20:11

VisioN