javascript正则表达式替换括号之间的空格 [英] javascript regex replace spaces between brackets

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

问题描述

如果在括号之间,我如何使用JS正则表达式替换空格的所有出现?
所以,我想要的是:

How can I use JS regex to replace all occurences of a space with the word SPACE, if between brackets? So, what I want is this:

myString = "a scentence (another scentence between brackets)"
myReplacedString = myString.replace(/*some regex*/)
//myReplacedString is now "a scentence (anotherSPACEscentenceSPACEbetweenSPACEbrackets)"

编辑:
我试过的是这个(我对正则表达式来说很新)

what I've tried is this (I'm quite new to regular expressions)

myReplacedString = myString.replace(/\(\s\)/, "SPACE");


推荐答案

您可以使用正则表达式:

You could perhaps use the regex:

/\s(?![^)]*\()/g

这将匹配任何空格,前面没有开口括号,空格和开口括号之间没有右边括号。

This will match any space without an opening bracket ahead of it, with no closing bracket in between the space and the opening bracket.

这是一个演示

编辑:我没有考虑句子不以括号结尾的情况。然而,@ thg435的正则表达式涵盖了它:

I hadn't considered cases where the sentences don't end with brackets. The regexp of @thg435 covers it, however:

/\s(?![^)]*(\(|$))/g

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

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