Javascript:正则表达式来摆脱括号和空格 [英] Javascript: Regex to escape parentheses and spaces

查看:99
本文介绍了Javascript:正则表达式来摆脱括号和空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我有一个字符串:(一些字符串),我需要它是 \(some\ string\)



现在,我这样做:

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

这是有用的,但它是丑陋的。有没有更清洁的方法去做?

解决方案

你可以这样做:

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

(?= ...)



[()] 是一个字符类。


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.

这篇关于Javascript:正则表达式来摆脱括号和空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆