0

i was trying to make a function that can take a char and a string as arguments and remove that char from the string.

function removeCharacter(char, str) {
    return str.replace(char, '');
}
ex: removeCharacter('r', "character") - > chaacte

Doing this way only removes the first char so I found out about the global Regex, but here is where I hit a wall...how can I make it so it can take any given char something like:

str.replace(/char/g, '')

I want pass that char as an argument in the function and remove all of them. Is there a way to this with regex or should i use a for statement? Or is there a better way?

Alin Faur
  • 1,091
  • 2
  • 9
  • 10

2 Answers2

3

You can construct a Regexp.

function removeCharacter(char, str) {
    var reg = new RegExp(char, 'g');
    return str.replace(reg, '');
}

[edit]
This answer only works for characters which are not special characters from the RegExp point of view (like '/', '(', '.'). Otherwise it will fail or have unexpected behaviour. cf @Wiktor's answer.

ValLeNain
  • 2,232
  • 1
  • 18
  • 37
2

To remove multiple occurrences of a char, you need to use a regex in JavaScript, a regex that is constructed with a g (global) modifier.

However, you can't just use /char/g, you need to declare the regex using a constructor notation, new RegExp(char, "g").

And since some chars are reserved, special regex metacharacters, you must escape them.

So, what you need is

function removeCharacter(char, str) {
    return str.replace(new RegExp(char.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), 'g'), '');
}
console.log(removeCharacter("(", "(abc(")); // => abc
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563