首页 > 解决方案 > 使用nodeJS和cheerio写入HTML文件时获取特殊字符而不是单引号

问题描述

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

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

想把它换成

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

所以我有以下节点代码:

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;)">

我怎样才能得到'而不是&apos;

标签: node.jshtml-entitiescheerio

解决方案


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

这是一个例子:

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

推荐阅读