使用HTML实体转换/替换html页面中的所有文本

时间:2018-05-22 10:44:27

标签: javascript jquery html-entities

我需要自动编辑保存在数据库中的一些html文件。我正在使用node.js来获取文件,然后使用jsdom和jquery来完成我需要的版本。

最后,我需要将文件保存回数据库,但是,所有文本都应该使用HTML实体。

所以,例如,这个页面:

<html>
 <header>
  <title>Título da página</title>
 </heade>
 <body>
  <h1> Aqui também há acentos </h1>
 </body>
</html>

应保存为:

<html>
 <header>
  <title>T&#xED;tulo da p&#xE1;gina</title>
 </heade>
 <body>
  <h1> Aqui tamb&#xE9;m h&#xE1; acentos </h1>
 </body>
</html>

似乎JSDOM API没有这个选项,但我也很难用jquery查找所有文本元素。 有什么建议吗?

谢谢,

PS:我尝试过的一些事情:

    function recursiveReplace(node) {
    if (node.nodeType == 3) { // text node
        node.nodeValue = node.nodeValue.replace("1", "۱");
    } else if (node.nodeType == 1) { // element
        $(node).contents().each(function () {
            recursiveReplace(this);
        });
    }
}

recursiveReplace(document.body);

来自Bruce Lindbloom

并且

$('body').text()
来自here

,它仅使用文本替换所有正文,而不是标记内的文本。

还有其他一些......

0 个答案:

没有答案