代码之家  ›  专栏  ›  技术社区  ›  Alexander Solonik

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

  •  1
  • Alexander Solonik  · 技术社区  · 7 年前

    <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; ??

    1 回复  |  直到 7 年前
        1
  •  3
  •   Nedko Dimitrov    7 年前

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

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