Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/440.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/70.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 我只想替换“1”之外的字符&引用;用正则表达式_Javascript_Html_Regex - Fatal编程技术网

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”)可能最简单、可读性最好的方法是首先拆分字符串,只处理子字符串部分,在子字符串部分中您实际上希望替换某些内容。