Javascript 我只想替换“1”之外的字符&引用;用正则表达式
我想用正则表达式得到结果Javascript 我只想替换“1”之外的字符&引用;用正则表达式,javascript,html,regex,Javascript,Html,Regex,我想用正则表达式得到结果 var text = "\"1test2test3\"test123test45test\"67test89\""; text.replaceAll(/\"(.*)\"/g, "boom"); boom 但是我想要 var text = "\"1test2test3\"test123test45test\"67test89\&
var text = "\"1test2test3\"test123test45test\"67test89\"";
text.replaceAll(/\"(.*)\"/g, "boom");
boom
但是我想要
var text = "\"1test2test3\"test123test45test\"67test89\"";
text.replaceAll(????, "boom");
"\"1test2test3\"boom123boom45boom\"67test89\"";
你可以用
.replace(/(“[^”]*”)| test/g,(x,y)=>y?y:“动臂”)
详细信息:
-捕获组1:a(“[^”]*”
”,然后捕获除a“
之外的任何零个或多个字符,然后捕获a“
”
-或|
-一个测试
字符串测试
(x,y)=>y?y:“boom”
替换意味着只要组1(y
)匹配,就会返回该组值,否则(如果在所有其他上下文中都找到了test
),就会返回boom
请参见JavaScript演示:
var text=“\'1test2test3\'test123test45test\'67test89\”;
console.log(text.replace(/(“[^”]*”)| test/g,(x,y)=>y?y:“boom”)代码>可能最简单、可读性最好的方法是首先拆分字符串,只处理子字符串部分,在子字符串部分中您实际上希望替换某些内容。