subharb
subharb

Reputation: 3472

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!

Upvotes: 0

Views: 720

Answers (2)

ratchet freak
ratchet freak

Reputation: 48226

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

Upvotes: 1

JAAulde
JAAulde

Reputation: 19560

You simply escape the "reserved" char in your RegExp:

var re = /abc\/def/;

You are probably having trouble with that because you are, for some reason, using a string as your RegExp and then evaling it...so odd.

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

is all you need.

If you INISIST on using a string, then you have to escape your escape:

var badwords = eval( "/foo|ba\\/r|baz/ig" );

This gets a backslash through the JS interpreter to make it to the RegExp engine.

Upvotes: 4

Related Questions