0

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!

2
  • 2
    Where's the slash in your code? Commented Jun 14, 2011 at 19:24
  • As asked by Álvaro, seeing what you're really trying to do would help us avoid making up random examples and get you on your way quicker. Commented Jun 14, 2011 at 19:28

2 Answers 2

4

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.

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

3 Comments

I'd give you +2 if I could. Because you didn't just answer the question but also provided some improvement to OP code.
For completeness: you can also new RegExp("foo|bar|baz", "ig") - developer.mozilla.org/en/JavaScript/Guide/Regular_Expressions
You can, but I don't know why people do something like that unless they need to concat a string together to make a dynamic pattern. I never understand the use of constructor functions where a literal would work. Note to the OP, however, if you use the RegExp constructor, you're back to using a string so you need to double escape the backslash.
1

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

1 Comment

Gerat, that's what I wanted to know to escape a character I have to put backslashes. Also thanks for the advidce of not using eval

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.