JQuery: Replace string with values ​​from array

Let's say I have something like this:

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

I want to remove all these values ​​from a string

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

The result is: The and ate the .

At the moment, replace() only replaces a single value from the array. How can I make all / several values ​​from an array be replaced in a string?

Thanks!

+8
javascript jquery arrays replace
source share
2 answers

You create your own regular expression or loop over a 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, '' ); 
+10
source share
 string.replace(new RegExp(array.join("|"), "g"), ""); 
+2
source share

All Articles