简体   繁体   中英

Ignoring html entities when using javascript regex replace

I'm trying to wrap 'a to z', '&', number characters and numbers with a <span> tag in a list that contains a mix of Latin and Korean text like so (simplified version):

 $('li').each(function() { var replaced_text = $(this).html().replace(/([a-zA-Z ])/g, '<span>$&</span>'); $(this).html(replaced_text) })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <ul> <li>&lt;서베이 WRM&gt;, 2019</li> <li>가나APAP다라 2018</li> <li>마바사아APAP 20&nbsp;17</li> <li>WKM마2바사아 20&nbsp;17</li> </ul>

But currently it is also replacing the letters in html entities such as &nbsp; &gt; &lt; &nbsp; &gt; &lt; , for example &lt; becomes &<span>l</span><span>t</span>; and so on.

So as per my title, how can i wrap those characters by using the replace function while avoiding html entities?

It would probably be easier to retrieve the textContent (or .text() , if you have to use the jQuery method) instead, which parses the entities to the displayed characters:

 $('li').each(function() { var replaced_text = $(this).text().replace(/([a-zA-Z ])/g, '<span>$&</span>'); $(this).html(replaced_text) })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <ul> <li>&lt;서베이 WRM&gt;, 2019</li> <li>가나APAP다라 2018</li> <li>마바사아APAP 20&nbsp;17</li> <li>WKM마2바사아 20&nbsp;17</li> </ul>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM