7

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
  • 669,327
  • 51
  • 454
  • 560
Kevin Whitaker
  • 11,071
  • 11
  • 49
  • 87
  • 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
  • 85,718
  • 5
  • 90
  • 121
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
  • 669,327
  • 51
  • 454
  • 560