1

I'm trying to escape the quotes (and apostrofes and escape char) in a text string in javascript:

var text = 'Escape " and \' and /.';
var rx = new RegExp('/([\'"])/g');
console.log(text, ' ==> ', text.replace(rx,'//\1'));​​​​​

What I expect to be output is Escape /" and /' and //., but instead I get Escape " and ' and /..

I just can't seem to get this working and don't know what's wrong.

Here's a JSFiddle: http://jsfiddle.net/hvtgf/

5
  • 2
    Why do you expect /? The escape character is `\`.. Commented Jul 4, 2012 at 19:26
  • Also, please stop using new RegExp('/([\'"])/g'); Javascript regular expressions are literals, that's like doing new String every time you want to define a string Commented Jul 4, 2012 at 19:27
  • @Rob W, because for the format I'm saving, I need / and I explicitely set / in the replacement string. Commented Jul 4, 2012 at 19:29
  • @Benjamin Grauenbaum: If I use text.replace(/([\'"])/g, '//\1') it doesn't replaces matched characters with empty string. Commented Jul 4, 2012 at 19:31
  • console.log("Escape ' and \" and /.".replace(/['"/]/g,function(str){return '/'+str})) Works for me Commented Jul 4, 2012 at 19:33

1 Answer 1

4

Escaping means using backslash \ but not slash /.

However, for your purposes you can try the following:

text.replace(/([/'"])/g, "/$1");

DEMO: http://jsfiddle.net/hvtgf/1/

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

2 Comments

Perfect! I guess the JS website I had as reference had the backreference syntax wrong.
@Martijn Hope it was not W3Schools :)

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.