JS.replace() with capture group usage
This fiddle contains a sample how to use JS.replace with RegExp and capture groups to show how to replace only the relevant portions of a text.
by Sascha
HTML
<div id="result">
</div>
<div id="sample">
<div><span class="option-icon-span"><i title="tf tf-changeprofile22"></i></span>Test (Profile).</div>
<div><span class="option-icon-span"><i title="tf tf-changeprofile22"></i></span>Test (Profile)</div>
<span title="low low low" class="Sehr">Sehr niedrig</span>
</div>
JavaScript
// [^<\/?]([\wäüÄÜöÖß]+)[!.< ]
var arrSearch = ['Test', 'Change', 'Test (Profile)', 'h', 'low', "Sehr"];
var arrReplace= ["FETT", "GROSS", "HÜHOTT", "was anderes", 'niedrig', "Very"];
var text = document.getElementById('sample').innerHTML;
for (var i in arrSearch) {
var word= arrSearch[i];
// var re= new RegExp("([^\\w<?/?\"])(" + word.replace('?', '\\?') + ")([^\w\"][!\.;,<]?)", "g");
var re= new RegExp("(>)(" + word.replace('?', '\\?') + ")([\.;,!]?<)", "g");
console.log(word);
var replaceWord= arrReplace[i];
text = text.replace(re, function (all, beforePart, replacePart, afterPart) {
console.log(all);
console.log(beforePart);
console.log(replacePart);
console.log(afterPart);
console.log('---------');
return beforePart+replaceWord+afterPart;
});
// text = text.replace(re, "$1, "+arrReplace[i]);
}
document.getElementById("result").innerText= text;
document.getElementById('sample').innerHTML = text;