Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add span for each letter, but avoid html tags using javascript

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">&lt;</span>
<span class="letter">b</span>
<span class="letter">r</span>
<span class="letter">&gt;</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

like image 746
momciloo Avatar asked Jun 27 '26 04:06

momciloo


1 Answers

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.

like image 182
trincot Avatar answered Jun 29 '26 18:06

trincot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!