如何判断字符串是否包含HTML实体(如& amp;)? [英] How to tell if a string contains HTML entity (like &)?

查看:342
本文介绍了如何判断字符串是否包含HTML实体(如& amp;)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个函数来检查一个特殊HTML实体数组的参数(比如用户输入'& amp'而不是'&'),然后在这些输入的实体周围添加一个范围。

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?

因此,如果传递了像我的名字这样的字符串& amp; ,那么将呈现我的名字是< span>& amp;< / span> 。如果一个特殊字符被列出两次 - 比如'我真的喜欢& amp;& amp;& amp; 它只会渲染每个元素的范围。用户还必须能够使用普通的&

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

推荐答案

您可以使用此正则表达式查找和包装实体:

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>');

它匹配word实体以及数字实体。例如:

It matches the "word" entities as well as numeric entities. For example:

'test & &amp; &#60;'.replace(/&(?:[a-z]+|#x?\d+);/gi, '<span>$&</span>');

输出:

test & <span>&amp;</span> <span>&#60;</span>

这篇关于如何判断字符串是否包含HTML实体(如&amp; amp;)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆