문제

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?

도움이 되었습니까?

해결책

you can do this:

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

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

[() ] is a character class.

다른 팁

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

x = x.replace(/[() ]/g, '\\$0')
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top