Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tell if a string contains HTML entity (like &)?

I'm trying to write a function that checks a parameter against an array of special HTML entities (like the user entered '&amp' instead of '&'), and then add a span around those entered entities.

How would I search through the string parameter to find this? Would it be a regex?

This is my code thus far:

 function ampersandKiller(input) {
 var specialCharacters = ['&', ' ']
 if($(specialCharacters).contains('&')) {
     alert('hey')
 } else {
     alert('nay')
 }
}

Obviously this doesn't work. Does anyone have any ideas?

So if a string like My name is &amp; was passed, it would render My name is <span>&amp;</span>. If a special character was listed twice -- like 'I really like &amp;&amp;&amp; it would just render the span around each element. The user must also be able to use the plain &.

like image 378
streetlight Avatar asked Oct 27 '25 10:10

streetlight


1 Answers

You could use this regular expression to find and wrap the entities:

input.replace(/&amp;|&nbsp;/g, '<span>$&</span>')

For any kind of entity, you could use this too:

input.replace(/&(?:[a-z]+|#\d+);/g, '<span>$&</span>');

It matches the "word" entities as well as numeric entities. For example:

'test & &amp; &#60;'.replace(/&(?:[a-z]+|#x?\d+);/gi, '<span>$&</span>');

Output:

test & <span>&amp;</span> <span>&#60;</span>
like image 60
Ja͢ck Avatar answered Oct 29 '25 00:10

Ja͢ck



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!