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;
}
Solution 2:
You could use this regular expression to find and wrap the entities:
input.replace(/&| /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 & & <'.replace(/&(?:[a-z]+|#x?\d+);/gi, '<span>$&</span>');
Output:
test & <span>&</span><span><</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('&'))
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 &)?"