为什么javascript字符串为空白字符& nbsp;不匹配? [英] Why does the javascript String whitespace character   not match?

查看:94
本文介绍了为什么javascript字符串为空白字符& nbsp;不匹配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在html中得到以下结构:

I got in html the following construct:

<div id="text">


       some&nbsp;text


   </div>

如果我修剪文本并测试它:

If I trim the text and test it with:

$("#text").text().trim() === "some text"

它返回false

it returns false also

$("#text").text().trim() === "some&nbsp;text"

返回false
但是

returns false but

/^some\s{1}text$/.test($("#text").text().trim())

返回true。
所以请告诉我,这里有什么问题。

returns true. So please tell me, what´s wrong here.

正如你的建议,我使用的是jQuery(1.6)。

As you would suggest, I am using jQuery (1.6).

推荐答案

那是因为没有空格(charCode 160)并不完全等于空格(charCode 32)

That's because the no breaking space (charCode 160) does not exactly equal to space (charCode 32)

jquery的 .text()将HTML实体编码为其直接unicode等价,因此& nbsp; 变为 String.fromCharCode(160)

jquery's .text() encodes HTML entities to their direct unicode equivalence, and so &nbsp; becomes String.fromCharCode(160)

您可以通过用普通空格替换所有非中断空格来解决它:

You can solve it by replaceing all the the non-breaking spaces with ordinary spaces:

d.text().replace(String.fromCharCode(160) /* no breaking space*/,
         " " /* ordinary space */) == "some text"

或更好:

d.text().replace(/\s/g /* all kinds of spaces*/,
         " " /* ordinary space */) == "some text"

这篇关于为什么javascript字符串为空白字符&amp; nbsp;不匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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