8

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!

1
  • Smells like homework. Well your example is invalid, running the array line will throw errors. And have you ever use a for loop or each() and new RegExp()? Hint, try that. Commented Dec 7, 2012 at 0:42

2 Answers 2

12

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, '' );
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.