8

Looking to backslash escape parentheses and spaces in a javascript string.

I have a string: (some string), and I need it to be \(some\ string\)

Right now, I'm doing it like this:

x = '(some string)'
x.replace('(','\\(')
x.replace(')','\\)')
x.replace(' ','\\ ')

That works, but it's ugly. Is there a cleaner way to go about it?

Barmar
  • 741,623
  • 53
  • 500
  • 612
Kevin Whitaker
  • 12,435
  • 12
  • 51
  • 89
  • Your code doesn't actually work. It will only replace the first occurrence of each character, not all of them. – Barmar Apr 04 '14 at 21:09

2 Answers2

14

you can do this:

x.replace(/(?=[() ])/g, '\\');

(?=...) is a lookahead assertion and means 'followed by'

[() ] is a character class.

Casimir et Hippolyte
  • 88,009
  • 5
  • 94
  • 125
  • What's the point of the lookahead here? Why not just match `/[() ]/g`? – talemyn Apr 04 '14 at 21:12
  • Ah, nevermind . . . I missed that you weren't using the capturing group in the replacement string. – talemyn Apr 04 '14 at 21:13
  • 1
    @talemyn: Yes, it is for this reason. However a solution as Barmar wrote works well too. – Casimir et Hippolyte Apr 04 '14 at 21:16
  • This worked - though now there is a new wrinkle. I need to add the dash `-` to the list of escaped characters, though that seems to eliminate everything which follows the dash from the string. – Kevin Whitaker Apr 04 '14 at 21:31
  • @KevinWhitaker: the dash is a special character in a character class (it is used to define character ranges), you can: 1) escape it, 2) put it at the begining of the character class, 3) put it at the end of the character class. – Casimir et Hippolyte Apr 04 '14 at 21:46
3

Use a regular expression, and $0 in the replacement string to substitute what was matched in the original:

x = x.replace(/[() ]/g, '\\$0')
Barmar
  • 741,623
  • 53
  • 500
  • 612