Search code examples
javascriptreplacecharacterreserved

Javascript replace several character including '/'


Im using this snippet to replace several characters in a string.

var badwords = eval("/foo|bar|baz/ig");
var text="foo the bar!";
document.write(text.replace(badwords, "***"));

But one of the characters I want to replace is '/'. I assume it's not working because it's a reserved character in regular expressions, but how can I get it done then?

Thanks!


Solution

  • first of DON'T USE EVAL it's the most evil function ever and fully unnecessary here

    var badwords = /foo|bar|baz/ig;
    

    works just as well (or use the new RegExp("foo|bar|baz","ig"); constructor)

    and when you want to have a / in the regex and a \ before the character you want to escape

    var badwords = /\/foo|bar|baz/ig;
    //or
    var badwords = new RegExp("\\/foo|bar|baz","ig");//double escape to escape the backslash in the string like one has to do in java