Javascript: regex to remove brackets and spaces

Looking for backslashes in square brackets and spaces in javascript string.

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

Now I am doing this:

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

It works, but it is ugly. Is there a cleaner way to do this?

+4
source share
2 answers

You can do it:

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

(?=...) - this statement in the form of a look and means "then"

[() ] - character class.

+11
source

Use the regex and $0in the replacement string to replace what was matched in the original:

x = x.replace(/[() ]/g, '\\$0')
+2
source

Source: https://habr.com/ru/post/1535101/


All Articles