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

给你一囗甜甜゛ 提交于 2019-12-10 17:52:14

问题


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


回答1:


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>



回答2:


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

    return input;
}

FIDDLE




回答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:

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

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



来源:https://stackoverflow.com/questions/13763205/how-to-tell-if-a-string-contains-html-entity-like-amp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!