I am trying to create a RegExp with a specific variable, which matches the variable exactly and replaces all possible occurrences. I found some different answers here but they do not seem to work with my problem.
This is my code:
for(var translation in translations) {
var regex = new RegExp("^" + translation + "$");
htmlContent = htmlContent.replace(regex, translations[translation][lang]);
}
"translations" is a JSON which looks like this:
{
"report_a_return-placeholder": {
"de": "Rücksendung melden",
"en": "Report a return",
"nl": "rapporteer een terugkeer",
"fi": "raportoi palautuksesta",
"da": "rapportere et afkast",
"no": "rapporter en retur",
"sv": "rapportera en avkastning"
}
}
And I am replacing inside the html:
<div id="Report_a_return">
<span>report_a_return-placeholder</span>
</div>
When I try creating the regex without the anchors, everything works fine and the regex replaces. However, I have some translations which start similarly so the regex replaced them even though it was not an exact match. That's why I need anchors. But when doing it like above, nothing is replaced!
Edit:
to clarify with a better example. I have the problem that e.g. "pay-placeholder" and "cofirm_and_pay-placeholder" both match "confirm_and_pay-placeholder". But I want "pay-placeholder" to only match "pay-placeholder" and "confirm_and_pay-placeholder" to match only that. That doesnt work rn. (if I just use newRexExp('pay-placeholder') this matches also the string "confirm_and_pay-placeholder")
^and$look for the beginning and the end of the string, which does not apply to the HTML. I would search for'<span>' + translation + '</span>'instead if you do need the regexp. But less prone to fail would be to actually select the div by id and then replace its child spans innerText with translation instead of using regexp.