2

The code I use at the moment is ugly because I have to write "replace" separately for every special character.

var str = ":''>";
str.replace("'","\\'").replace(">","\\>");

I would like to prepend backslash to < > * ( ) and ? through regex.

Pinky
  • 103
  • 1
  • 4
  • 9

1 Answers1

8

Using a regex that matches the characters with a character set, you could try:

str = str.replace(/([<>*()?])/g, "\\$1");

DEMO: http://jsfiddle.net/8ar3Z/

It matches any of the characters inside of the [ ] (the ones you specified), captures them with the surrounding () (so that it can be referenced as $1 in the replaced text part), and then prepends with \\.


UPDATE:

As a suggestion from Mr. @T.J.Crowder, it is unnecessary to capture with (), changing $1 to $&, written as:

str = str.replace(/[<>*()?]/g, "\\$&");

DEMO: http://jsfiddle.net/8ar3Z/1/


References:

Ian
  • 50,146
  • 13
  • 101
  • 111
  • 2
    +1 (in fact, I was your first upvote!), but you don't need a capture group: `str = str.replace(/[<>*()?]/g, "\\$&");` – T.J. Crowder Jun 21 '13 at 15:24
  • @T.J.Crowder Hmm interesting. I've never strayed from `$n`, so I didn't realize `$&` would work like that. Thanks, I'll update! And woah, you deserve a prize for being first, for sure... :) – Ian Jun 21 '13 at 15:26
  • @ Ian: Not like the capture group is doing any harm. :-) But perhaps it's *slightly* simpler for newbies without... – T.J. Crowder Jun 21 '13 at 15:26
  • 1
    @T.J.Crowder You're absolutely right though! And it doesn't hurt to include/explain both versions. Just to make sure I understand, if you were trying to capture two different things in the same regex, you'd **need** to use `$1` and `$2` (with `( )`), right? I just want to make sure I'm not thinking through this wrong – Ian Jun 21 '13 at 15:32
  • 1
    @ Ian: Yeah, `$&` is the *entire* matched substring (including any captures if you've used them). So for instance: `"123 456".replace(/\d(\d)?\d/g, "$& [$1]")` gives you `"123 [2] 456 [5]"` because `$&` is the entire match (`"123"` the first time, then `"456"` the second time) and `$1` is the capture group (`"2"` and `"5"`). – T.J. Crowder Jun 21 '13 at 15:39
  • @T.J.Crowder I should've just tested...that makes perfect sense. Thanks :) (un)fortunately I don't have to work with regexes outside of SO too much, so I didn't want to assume (even after reading MDN docs) – Ian Jun 21 '13 at 15:39