Javascript: Regex to escape parentheses and spaces

别说谁变了你拦得住时间么 提交于 2019-12-10 14:31:22

问题


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?


回答1:


you can do this:

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

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

[() ] is a character class.




回答2:


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

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


来源:https://stackoverflow.com/questions/22872974/javascript-regex-to-escape-parentheses-and-spaces

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!