1

Is there a way to replace all occurrences in string giving an array as a parameter in replace() method.

For example:

Having this string: "ABCDEFG"

And having this array: ['A','D','F']

It is possible to replace the same letters in the string with something else? Something like:

"ABCDEFG".replace(['A','D','F'], '')

So the final result be: "BCEG"

3
  • Is "ABCDEFG".replace(/A|D|F/g, '') would be fine, or it has to be dynamic with the array ? Commented Mar 27, 2018 at 14:31
  • Not in the replace method (given you don't want to touch the prototype). You could write your own function, though Commented Mar 27, 2018 at 14:31
  • @Leyffda is a dynamic array, anyway this gives me an idea Commented Mar 27, 2018 at 14:32

5 Answers 5

2

You can loop through your array:

var str = "ABCDEFG";
['A','D','F'].forEach(c => str = str.replace(c, '*'))
console.log(str);

Sign up to request clarification or add additional context in comments.

Comments

0

Kind of:

 "ABCDEFG".replace(new RegExp(['A','D','F'].join("|")), '')

Comments

0

There is actually a way to do this from an Array.

You'll need to create a RegEx dynamically :

let arr = ['A','D','F'];
let expression = arr.join('|');
let rx = new RegExp(expression, 'g');

console.log("ABCDEFG".replace(rx,''));

Comments

0

If you want an array as input:

'ABCDEF'.replace(new RegExp(['A','D','F'].join('|'), 'g'), '')

By using the 'g' flag, it will replace all occurrences of 'A', 'D' or 'F' in the string.

You could also do this in a simpler way:

'ABCDEF'.replace(/A|D|F/g, '')

Comments

0

Here's a general function that uses regex similar to the other answers, but allows you to pass in whatever replacement string you like:

const str = 'ABCDEFG';
const arr = ['A', 'D', 'F'];

function replace(str, arr, r) {
  const regex = new RegExp(arr.join('|'), 'g');
  return str.replace(regex, p => r);
}

console.log(replace(str, arr, ''));
console.log(replace(str, arr, 'bob'));

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.