Javascript RegEx和转义所需的建议

时间:2013-06-27 10:10:30

标签: javascript regex negative-lookahead

我想用替换(模板语言)替换一个或多个问号,如:

var translation = "this is a ???";
console.log(translation.replace(/(\?+)/g, "replacement")); //this is a replacement

但是现在,我最近遇到了一个问题,问题实际上是一个问题,不应该被转义。我决定将~作为逃避角色,所以不应该转义:

var translation = "this should not be escaped, cause it's a question, is it~?";
console.log(translation.replace(/[^~](\?+)/g, "replacement")); 

到目前为止工作。但是,如果我使用多个问号(模板语法的要求),我最终会得到废话:

var translation = "this should not be escaped, cause it's a question, is it~???";
console.log(translation.replace(/[^~](\?+)/g, "replacement")); 
//this should not be escaped, cause it's a question, is it~replacement  <-- ???

有关如何做到这一点的任何建议?一个经典的\作为逃避角色会让我比~更快乐,但我也遇到了问题。

2 个答案:

答案 0 :(得分:1)

~应该只用于逃避一个字符(我认为可以预期)。模板的用户可以编写~?~?~?来转义多个字符。

至于替换,[^~]仍会选择一个字符。

translation.replace(/([^~])\?+/g", "$1replacement")

$1将再次插入所选字符

答案 1 :(得分:1)

使用negative lookbehind

translation.replace(/(<!~)\?+/g, "replacement");