Skip to content Skip to sidebar Skip to footer

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 '&' instead of '&'), and then add a span around t

Solution 1:

functionhtmlEntityChecker(input) {
    var characterArray = ['&', ' '];
    $.each(characterArray, function(idx, ent) {
        if (input.indexOf(ent) != -1) {
            var re = newRegExp(ent, "g");
            input = input.replace(re, '<span>' + ent + '</span>');
        }
    });

    return input;
}

FIDDLE

Solution 2:

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>

Solution 3:

Another option would be to make the browser do a decode for you and check if the length is any different... check this question to see how to unescape the entities. You can then compare the length of the original string with the length of the decoded. Example below:

functionhtmlDecode(input){
    var e = document.createElement('div');
    e.innerHTML = input;
    return e.childNodes.length === 0 ? "" : e.childNodes[0].nodeValue;
}
functionhasEntities(input) {
    if (input.length != htmlDecode(input).length) {
       returntrue;
    }
    returnfalse;
}
alert(hasEntities('a'))
alert(hasEntities('&amp;'))

The above will show two alerts. First false and then true.

Post a Comment for "How To Tell If A String Contains Html Entity (like &)?"