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?
[[XYZ]]-are a fixed prefix? If it is, you can do it in a very simpler way.