更换& nbsp;来自javascript dom文本节点 [英] Replacing   from javascript dom text node
问题描述
我正在使用javascript处理xhtml。我通过连接所有子节点的nodeValue获取div节点的文本内容,其中nodeType == Node.TEXT_NODE。
I am processing xhtml using javascript. I am getting the text content for a div node by concatenating the nodeValue of all child nodes where nodeType == Node.TEXT_NODE.
结果字符串有时包含非破坏性太空实体。如何用常规空格字符替换它?
The resulting string sometimes contains a non-breaking space entity. How do I replace this with a regular space character?
我的div看起来像这样......
My div looks like this...
< div>< b> Expires On< / b> 2009年9月30日06:30& nbsp; AM< / div>
以下建议在网络不起作用:
The following suggestions found on the web did not work:
var cleanText = text.replace(/^\xa0*([^\xa0]*)\xa0*$/g,"");
var cleanText = replaceHtmlEntities(text);
var replaceHtmlEntites = (function() {
var translate_re = /&(nbsp|amp|quot|lt|gt);/g;
var translate = {
"nbsp": " ",
"amp" : "&",
"quot": "\"",
"lt" : "<",
"gt" : ">"
};
return function(s) {
return ( s.replace(translate_re, function(match, entity) {
return translate[entity];
}) );
}
})();
有什么建议吗?
推荐答案
这比你制作它容易得多。文本节点将不会包含文字字符串& nbsp;
,它将具有代码为160的相应字符。
This is much easier than you're making it. The text node will not have the literal string " "
in it, it'll have have the corresponding character with code 160.
function replaceNbsps(str) {
var re = new RegExp(String.fromCharCode(160), "g");
return str.replace(re, " ");
}
textNode.nodeValue = replaceNbsps(textNode.nodeValue);
UPDATE
更容易:
textNode.nodeValue = textNode.nodeValue.replace(/\u00a0/g, " ");
这篇关于更换& nbsp;来自javascript dom文本节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!