node.js - 使用nodeJS和cheerio写入HTML文件时获取特殊字符而不是单引号

标签 node.js html-entities cheerio

我只是在玩node,所以我想替换我的html文件中的以下html

<div class="replace" onclick="opennewtab('one')">

想替换它

<div class="replace" onclick="replacedFunc('12345&')">

所以我有以下 Node 代码:

let fs = require('fs'),
cheerio = require('cheerio');

$ = cheerio.load( fs.readFileSync( `${__dirname}/res/writetojs.html` ) );
$('.replace').attr('onclick' , "replacedFunc('12345')");
console.log($.html());
inner_content =  $.html();
fs.writeFileSync( `${__dirname}/res/newwritetojs.html` , inner_content, 'utf8');

但是我得到的是

<div class="replace" onclick="replacedFunc(&apos;12345&apos;)">

我怎样才能得到'而不是'??

最佳答案

Cheerio 默认情况下正在解码 HTML 实体,需要时您可以通过传递 decodeEntities: false 选项来关闭此功能

这是一个例子:

$ = cheerio.load( fs.readFileSync( `${__dirname}/res/writetojs.html` ), {decodeEntities: false} );

关于node.js - 使用nodeJS和cheerio写入HTML文件时获取特殊字符而不是单引号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53515136/

相关文章:

node.js - Cheerio 中的 get() 函数有什么作用?

node.js - 微服务——每个 CRUD 是一个服务吗

cocoa - 如何使用 Cocoa 可靠地将 £ 等特殊字符转换为 HTML 等效字符?

javascript - 如何使用cheerio用一个标签包装元素的子元素/子元素?

php - 如何使用 CodeIgniter 在 MySQL 中插入 HTML 实体?

c - 在字符串中搜索和替换

jquery - 为什么 Cheerio 不像 jquery 那样工作(不同的结果)

node.js - SQL Server 未与 Node 应用程序连接

Node.js Socket.IO 客户端 'unhandled socket.io url'

Javascript 将新字段分配给对象