Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/397.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正则表达式替换下一个匹配项_Javascript_Regex_String_Replace_Match - Fatal编程技术网

Javascript正则表达式替换下一个匹配项

Javascript正则表达式替换下一个匹配项,javascript,regex,string,replace,match,Javascript,Regex,String,Replace,Match,许多你可能认为相关的问题会说“use/g”。那不是我想要的。一定有办法做到这一点。我所拥有的是: <script> var myString = "DECLARE DeCLARE Declare DECLARE"; var arr = myString.match(new RegExp("[Dd]eclare|DECLARE","gm")); var clr = "#F00"; for(var i=0; i<arr.length; i++) { myString = m

许多你可能认为相关的问题会说“use/g”。那不是我想要的。一定有办法做到这一点。我所拥有的是:

<script>
var myString = "DECLARE DeCLARE Declare DECLARE";
var arr = myString.match(new RegExp("[Dd]eclare|DECLARE","gm"));
var clr = "#F00";
for(var i=0; i<arr.length; i++)
{
    myString = myString.replace(arr[i],"-"+arr[i]+"-");
}
document.write(myString);
</script>
期望输出:

-DECLARE- DeCLARE -Declare- -DECLARE-

在全局正则表达式中使用捕获组,并在
.replace()
中使用捕获值


在全局正则表达式中使用捕获组,并在
.replace()
中使用捕获值

-DECLARE- DeCLARE -Declare- -DECLARE-
var myString = "DECLARE DeCLARE Declare DECLARE";

// ---capture-----------v------------------v
var regex = new RegExp("([Dd]eclare|DECLARE)","gm");

// ---first capture------------------v
myString = myString.replace(regex,"-$1-");

document.write(myString); // "-DECLARE- DeCLARE -Declare- -DECLARE-"