如何判断字符串是否包含HTML实体(如& amp;)? [英] How to tell if a string contains HTML entity (like &)?
问题描述
我正在尝试编写一个函数来检查一个特殊HTML实体数组的参数(比如用户输入'& amp'而不是'&'),然后在这些输入的实体周围添加一个范围。
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 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?
因此,如果传递了像我的名字这样的字符串& amp;
,那么将呈现我的名字是< span>& amp;< / span>
。如果一个特殊字符被列出两次 - 比如'我真的喜欢& amp;& amp;& amp;
它只会渲染每个元素的范围。用户还必须能够使用普通的&
。
So if a string like My name is &
was passed, it would render My name is <span>&</span>
. If a special character was listed twice -- like 'I really like &&&
it would just render the span around each element. The user must also be able to use the plain &
.
推荐答案
您可以使用此正则表达式查找和包装实体:
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>');
它匹配word实体以及数字实体。例如:
It matches the "word" entities as well as numeric entities. For example:
'test & & <'.replace(/&(?:[a-z]+|#x?\d+);/gi, '<span>$&</span>');
输出:
test & <span>&</span> <span><</span>
这篇关于如何判断字符串是否包含HTML实体(如& amp;)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!