JavaScript 字符串中如何表示不间断空格?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5237989/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How is a non-breaking space represented in a JavaScript string?
提问by Phillip Senn
This apparently is not working:
这显然不起作用:
X = $td.text();
if (X == ' ') {
X = '';
}
Is there something about a non-breaking space or the ampersand that JavaScript doesn't like?
有没有关于不间断空格或 JavaScript 不喜欢的&符号的东西?
回答by Andrew Moore
is a HTML entity. When doing .text()
, all HTML entities are decoded to their character values.
是一个 HTML 实体。这样做时.text()
,所有 HTML 实体都被解码为它们的字符值。
Instead of comparing using the entity, compare using the actual raw character:
不使用实体进行比较,而是使用实际的原始字符进行比较:
var x = td.text();
if (x == '\xa0') { // Non-breakable space is char 0xa0 (160 dec)
x = '';
}
Or you can also create the character from the character code manually it in its Javascript escaped form:
或者,您也可以从字符代码手动创建字符,以 Javascript 转义形式:
var x = td.text();
if (x == String.fromCharCode(160)) { // Non-breakable space is char 160
x = '';
}
More information about String.fromCharCode
is available here:
有关更多信息,String.fromCharCode
请访问:
More information about character codes for different charsets are available here:
此处提供有关不同字符集的字符代码的更多信息:
回答by Brad Christie
Remember that .text()
strips out markup, thus I don't believe you're going to find
in a non-markup result.
请记住,.text()
删除标记,因此我不相信您会
在非标记结果中找到。
Made in to an answer....
在回答中......
var p = $('<p>').html(' ');
if (p.text() == String.fromCharCode(160) && p.text() == '\xA0')
alert('Character 160');
Shows an alert, as the ASCII equivalent of the markup is returned instead.
显示警报,因为返回的是标记的 ASCII 等价物。
回答by JAAulde
That entity is converted to the char it represents when the browser renders the page. JS (jQuery) reads the rendered page, thus it will not encounter such a text sequence. The only way it could encounter such a thing is if you're double encoding entities.
当浏览器呈现页面时,该实体将转换为它所代表的字符。JS (jQuery) 读取渲染的页面,因此不会遇到这样的文本序列。它可能遇到这种事情的唯一方法是如果您是双重编码实体。
回答by Jacob Mattison
The jQuery docs for text()
says
jQuery 文档text()
说
Due to variations in the HTML parsers in different browsers, the text returned may vary in newlines and other white space.
由于不同浏览器中 HTML 解析器的差异,返回的文本在换行符和其他空白处可能会有所不同。
I'd use $td.html()
instead.
我会用$td.html()
。