仅当子字符串出现在引号之外且不在javascript中的引号内时才替换子字符串

时间:2013-05-29 12:16:52

标签: javascript regex

/+(?=([^"\\]*(\\.|"([^"\\]*\\.)*[^"\\]*"))*[^"]*$)/g, "&&"

我用这个正则表达式替换了+&&但我如何用“&&”

替换字符串“和”
str = "Loop(this and that is "Help and enjoy")";

它应该返回:Loop(this && that is "Help and enjoy")

2 个答案:

答案 0 :(得分:1)

您是否尝试过更换+

/(?:and)(?=([^"\\]*(\\.|"([^"\\]*\\.)*[^"\\]*"))*[^"]*$)/g, "&&"

答案 1 :(得分:1)

这样做的一种方法是匹配之前的双引号内容:

var corr = {"and": "&&", "+": "&&"};

str.replace(/"[^"]+"|\+|\band\b/g, function(match) {
    return corr[match] || match;
});