Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Regex to escape parentheses and spaces

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?

like image 799
Kevin Whitaker Avatar asked Apr 04 '14 21:04

Kevin Whitaker


1 Answers

you can do this:

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

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

[() ] is a character class.

like image 59
Casimir et Hippolyte Avatar answered Sep 18 '22 14:09

Casimir et Hippolyte