1

I need to replace a occurrences within a string with variable occurrences and then reconstruct the string. I figured some regex magic with javascript and it should be a snap. However, after much fussing and banging of my head I reach out to my stack overflow brothers and sisters for their keen eye.

I am trying to remove [[XYZ]] as in the following code:

<!DOCTYPE html>
<html>
<body>

<p>Click the button to replace and switch:</p>

<p id="demo">{
  "[[XYZ]]-ENGINES": "L300",
  "[[XYZ]]-INTERIOR": "BURGCOMDDD",
  "[[XYZ]]-BASEBOAT": "PUTT"
}
</p>

<button onclick="myFunction()">Try it</button>

<script>

function replaceAll(string, find, replace) {
    return string.replace(new RegExp(find, 'g'), replace);
}

function myFunction() {

    var str = document.getElementById("demo").innerHTML; 
    var replaceString = "\"[[XYZ]]?-*(.+)\": \"([A-Z0-9]+)\"?,*"
    var replacementString = '$1/$2 = true,';

        newstr = replaceAll(str, replaceString, replacementString)
        alert(newstr)

}

</script>

</body>
</html>

BUT, when I run it returns:

{
    [XYZ]]-ENGINES/L300 = true,
    [XYZ]]-INTERIOR/BURGCOMDDD = true,
    [XYZ]]-BASEBOAT/PUTT = true,
}

when it should be:

{
    ENGINES/L300 = true,
    INTERIOR/BURGCOMDDD = true,
    BASEBOAT/PUTT = true,
}

Wh?

2
  • Is the [[XYZ]]- are a fixed prefix? If it is, you can do it in a very simpler way. Commented May 25, 2015 at 21:12
  • Yes it is a fixed prefix. By the way, none of the other answers have worked. Commented May 25, 2015 at 23:20

3 Answers 3

1

You must escape [ with \. But wait, since you use a string instead of a regex literal, you must escape \ with another \:

'"[[XYZ]]-ENGINES": "L300"'.replace(
    new RegExp("\"\\[\\[XYZ]]?-*(.+)\": \"([A-Z0-9]+)\"?,*", 'g'),
    '$1/$2 = true,'
);
Sign up to request clarification or add additional context in comments.

1 Comment

This worked!! It was the double \\ that was the secret ingredient. thanks.
0

Try using

function myFunction() {
    var str = document.getElementById("demo").innerHTML; 
    var newstr = str.replace(/\[\[XYZ\]\]-/g, "");
    alert(newstr);
}

You will need to escape special characters such as [ or ]

I removed your function, I hope that's okay.

Comments

0

You need to escape [ and ]:

var replaceString = "\"\[\[XYZ\]\]?-*(.+)\": \"([A-Z0-9]+)\"?,*"

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.