What I want to do is turn this:
<DIV>One Two Three</DIV>
Into this:
HTML
<DIV><SPAN id="One"></SPAN><SPAN id="Two"></SPAN><SPAN id="Three"></SPAN></DIV>
CSS
#One { background-image: url('one.png'); }
#Two { background-image: url('two.png'); }
#Three { background-image: url('three.png'); }
I have a couple problems. First, I know the RegEx command:
bw(.*?)+b
Will pick up every word in a string, but it inadvertently turns every instance of DIV into a match. I tried using positive lookups so that DIV is not picked up:
(?<=>)bw(.*?)+b(?=<)
But it resulted in turning "One Two Three" into a unified match.
Secondly, I have this jQuery code that will turn my match criteria into SPAN IDs.
$("DIV").each(function() {
$(this).html($(this).html().replace(/bw(.*?)+b/gi, "<SPAN id="$0"></SPAN>"));
});
But then I found Alex Turpin’s answer to wrapping each word of an element inside a SPAN tag, and wanted to apply that. It almost worked: I was able to give each word in the string a SPAN element, but it would not preserve the id parameter. What am I missing to make this all work?
UPDATE: Anant provided a promising solution in the comments section. During my test, I ran into a weird bug where it picked up all instances of a placeholder string that was serving as a personal reminder to replace the word later. They look like this:
<DIV>
<DIV class="Something">One Two Three</DIV></DIV>
<DIV>
<DIV class="Something">TEMP</DIV></DIV>
<DIV>
<DIV class="Something">TEMP</DIV></DIV>
When the code was applied, it turned into this:
<DIV>
<DIV class="Something"><SPAN style="background-image: url(one.png)"></SPAN><SPAN style="background-image: url(two.png)"></SPAN><SPAN style="background-image: url(threeTEMPTEMP.png)"></SPAN></DIV></DIV>
<DIV>
<DIV class="Something"><SPAN style="background-image: url(one.png)"></SPAN><SPAN style="background-image: url(two.png)"></SPAN><SPAN style="background-image: url(threeTEMPTEMP.png)"></SPAN></DIV></DIV>
<DIV>
<DIV class="Something"><SPAN style="background-image: url(one.png)"></SPAN><SPAN style="background-image: url(two.png)"></SPAN><SPAN style="background-image: url(threeTEMPTEMP.png)"></SPAN></DIV></DIV>
This bug was solved by simply deleting all traces of the word TEMP from the HTML. You will also notice the code duplicating itself in every Something class. All that’s left is for the code to take each instance of Something class individually.
2
Answers
You are missing a regex that works:
Also, your replace string should use
$&
and not$0
:Try it on regex101.com.
This is how your current regex works:
Try it on regex101.com to see the difference between them.
Try it:
Apply an extra class to the divs where you want to do the replacement work:
Check below code snippet: