Search code examples
javascriptjqueryhtml-entities

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 &.


Solution

  • 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>