I have a list of strings which should be wrapped by with some class in the HTML markup before or after appending to DOM (both options are acceptable). The issue is that the markup has a lot of "garbage" inside - formatting tags, styles, wrapping to another DOM elements, which should left after the replacement. See example below:
<custom-tag>Word4<span style='font-family:"Candara","sans-serif"'>Word1 Word2</span>Word3</custom-tag>
<custom-tag>Word1<span style='font-family:"Candara","sans-serif"'>Word2<br>Word1<b>Word6</b></span></custom-tag>
Given the list of ['Word1', 'Word4', 'd6'] I should receive as result:
<custom-tag><span class="replaced">Word4</span><span style='font-family:"Candara","sans-serif"'><span class="replaced">Word1</span> Word2</span>Word3</custom-tag>
<custom-tag><span class="replaced">Word1</span><span style='font-family:"Candara","sans-serif"'>Word2<br><span class="replaced">Word1</span><b>Wor<span class="replaced">d6</span></b></span></custom-tag>
So:
- Replace only plain strings, don't touch tags and styles
- Replace all strings from the list in each content (not only the first one)
I have started from the regex, and wrote the one which takes the matches the content with the one term from list.
<custom-tag>.*?|(Word1).*?<\/custom-tag>
Unfortunately I'm not an expert in regex, so I need a help. Ideally it should be 1 regex, which matches all strings from a list and excludes the tags and styles. Another option - write a script which uses the DOM API and make the same as described above. Thank you for any ideas.