最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript: Regex to escape parentheses and spaces - Stack Overflow

programmeradmin1浏览0评论

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?

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?

Share Improve this question edited Apr 4, 2014 at 21:05 Barmar 781k56 gold badges545 silver badges659 bronze badges asked Apr 4, 2014 at 21:03 Kevin WhitakerKevin Whitaker 13.4k13 gold badges53 silver badges94 bronze badges 1
  • Your code doesn't actually work. It will only replace the first occurrence of each character, not all of them. – Barmar Commented Apr 4, 2014 at 21:09
Add a comment  | 

2 Answers 2

Reset to default 14

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')
发布评论

评论列表(0)

  1. 暂无评论