I have a string
var string = "Selected<br>Works"
From which I need to wrap each letter with <span></span>, avoiding wrapping the <br> tag within span. Is it possible with regex?
I made it to:
'Selected<br>Works'.replace(/\S/g, '<span class="letter">$&</span>')
Which returns:
<span class="letter">S</span>
<span class="letter">e</span>
<span class="letter">l</span>
<span class="letter">e</span>
<span class="letter">c</span>
<span class="letter">t</span>
<span class="letter">e</span>
<span class="letter">d</span>
<span class="letter"><</span>
<span class="letter">b</span>
<span class="letter">r</span>
<span class="letter">></span>
<span class="letter">W</span>
<span class="letter">o</span>
<span class="letter">r</span>
<span class="letter">k</span>
<span class="letter">s</span>
While desired result is:
<span class="letter">S</span>
<span class="letter">e</span>
<span class="letter">l</span>
<span class="letter">e</span>
<span class="letter">c</span>
<span class="letter">t</span>
<span class="letter">e</span>
<span class="letter">d</span>
<br>
<span class="letter">W</span>
<span class="letter">o</span>
<span class="letter">r</span>
<span class="letter">k</span>
<span class="letter">s</span>
Other string examples are:
Art Direction<br>Creative Concept<br>UX/UI Design
Digital Branding<br>Website
You could use replace with a lookahead kind of regular expression:
var string = "Selected<br>Works",
result = string.replace(/(?![^<]*>)[^<]/g, c => `<span>${c}</span>\n`);
console.log(result);
This will also skip other tags, like <p> or </canvas>. Still, it will not be able to cope with more complex HTML (including scripts, comments, ...), for which regular expressions are not suitable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With