从 javascript 文本节点替换

我正在使用 javascript 处理 xhtml。我通过连接 nodeType = = Node.TEXT _ NODE 的所有子节点的 nodeValue 来获取 div 节点的文本内容。

生成的字符串有时包含一个不换行空格实体,如何用常规空格字符替换它?

我的 Div 看起来像这样..。

<div><b>Expires On</b> Sep 30, 2009 06:30&nbsp;AM</div>

在网上发现的下列建议不起作用:

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];
}) );
}
})();

有什么建议吗?

135885 次浏览

当你用“ var foo = function() {...};”定义一个函数时,这个函数只定义了 之后那一行。换句话说,试试这个:

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];
}) );
}
})();


var cleanText = text.replace(/^\xa0*([^\xa0]*)\xa0*$/g,"");
cleanText = replaceHtmlEntities(text);

编辑 : 另外,只在第一次声明变量时使用“ var”(在 cleanText变量上使用了两次)。

编辑2 : 问题在于函数名的拼写。有“ var replace Html实体 =”。应该是“ var replace Html(法语) =”

如果您只需要替换 &nbsp;,那么您可以使用一个简单得多的 regex:

var textWithNBSpaceReplaced = originalText.replace(/&nbsp;/g, ' ');

另外,在 div 示例中有一个输入错误,它说的是 &nnbsp;而不是 &nbsp;

这比你做的容易多了。文本节点不包含字符串 "&nbsp;",而是包含代码160的对应字符。

function replaceNbsps(str) {
var re = new RegExp(String.fromCharCode(160), "g");
return str.replace(re, " ");
}


textNode.nodeValue = replaceNbsps(textNode.nodeValue);

更新

甚至更简单:

textNode.nodeValue = textNode.nodeValue.replace(/\u00a0/g, " ");

第一句台词很糟糕,只需要是:

var cleanText = text.replace(/\xA0/g,' ');

这应该就够了。

我用了这个,它起作用了:

var cleanText = text.replace(/&amp;nbsp;/g,"");
var text = "&quot;&nbsp;&amp;&lt;&gt;";
text = text.replaceHtmlEntites();


String.prototype.replaceHtmlEntites = function() {
var s = this;
var translate_re = /&(nbsp|amp|quot|lt|gt);/g;
var translate = {"nbsp": " ","amp" : "&","quot": "\"","lt"  : "<","gt"  : ">"};
return ( s.replace(translate_re, function(match, entity) {
return translate[entity];
}) );
};

试试这个... 这个对我管用

删除 &;之间的所有符号,所有这些符号。如果你只是想摆脱他们。

text.replace(/&.*;/g,'');

对我来说,替换不起作用..。 试试这个代码:

str = str.split("&quot;").join('"');

破解这个问题的一种方法是使用一些换行符和一个标记将任何空行替换为两个或多个空格。然后贴上标记,用这个标记替换段落到换行符。

// replace empty lines with "EMPTY_LINE"
rawMdText = rawMdText.replace(/\n  +(?=\n)/g, "\n\nEMPTY_LINE\n");
// put <br> at the end of any other line with two spaces
rawMdText = rawMdText.replace(/  +\n/, "<br>\n");


// parse
let rawHtml = markdownParse(rawMdText);


// for any paragraphs that end with a newline (injected above)
// and are followed by multiple empty lines leading to
// another paragraph, condense them into one paragraph
mdHtml = mdHtml.replace(/(<br>\s*<\/p>\s*)(<p>EMPTY_LINE<\/p>\s*)+(<p>)/g, (match) => {
return match.match(/EMPTY_LINE/g).map(() => "<br>").join("");
});


// for basic newlines, just replace them
mdHtml = mdHtml.replace(/<p>EMPTY_LINE<\/p>/g, "<br>");

这个函数的作用是找到每一行只有几个空格 + 的新行。它使用“向前看”,以便它从下一个替换的正确位置开始,如果没有它,它将在一行中断开两行。

然后 markdown 将这些行解析为只包含标记“ EMPTY _ LINE”的段落。因此,您可以遍历 rawHtml 并用换行符替换它们。

作为奖励,替换功能将浓缩所有行分段成一个上段和下段,如果他们存在。

实际上,你可以这样使用它:

A line with spaces at end
  

  

and empty lines with spaces in between will condense into a multi-line paragraph.


A line with no spaces at end
  

  

and lines with spaces in between will be two paragraphs with extra lines between.

结果是这样的:

<p>
A line with spaces at end<br>
<br>
<br>
and empty lines with spaces in between will condense into a multi-line paragraph.
</p>


<p>A line with no spaces at end</p>
<br>
<br>
<p>and lines with spaces in between will be two paragraphs with extra lines between.</p>

它遍历对象数组中的每个值并进行转换

也许这对某人有帮助... 纯 javascript 函数。

var array = [{text: 'test &amp; & "', id:1}, {text: 'test222 &quot; \' 22222 "', id:2}];


console.log('in', JSON.stringify(array));
    

array.map((object, i) => {
//console.log('i', i, object);
Object.keys(object).map(key => {
var value = String(object[key]);
                

var replacewith = {'&amp;': '&', '&lt;': '<', '&gt;': '>', '&quot;': '"', '&#039;': '\''};
                

['&amp;', '&lt;', '&gt;', '&quot;', '&#039;'].map(checkme => {
if(value.indexOf(checkme) != -1){
console.log('htmlConvertBack found ' + checkme, value);
                        

var re = new RegExp(checkme, 'g');
                        

object[key] = value.replace(re, replacewith[checkme]);
}
});


});
});
    

console.log('out', JSON.stringify(array));