1

Many questions you might think are related will say something like "use /g". That's not what I'm after. There must be a way to do this. What I have is the following:

<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>

The output:

--DECLARE-- DeCLARE -Declare- DECLARE

Desired output:

-DECLARE- DeCLARE -Declare- -DECLARE-

1 Answer 1

1

Use a capturing group in the global regex, and use the captured value in the .replace().

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-"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.