【发布时间】:2013-06-27 10:10:29
【问题描述】:
我想用替换(模板语言)替换一个或多个问号,如下所示:
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 <-- ???
关于如何做到这一点的任何建议?一个经典的\ 作为转义字符会让我比~ 更快乐,但我也遇到了问题。
【问题讨论】:
-
一个转义字符通常只转义一个字符——让
~转义一个系列的?是不寻常的。相反,写~?~?~?是有意义的 -
@ExplosionPills 这实际上是一个好点。
-
对于需要 jsfiddle 链接来处理此问题的人jsfiddle.net/A4SGh
-
jsfiddle.net/A4SGh/1 barmar 的解决方案有效!!
标签: javascript regex negative-lookahead