utils.js 1.52 KB
'use strict';
const _ = require('lodash');
const cheerio = require('cheerio');

const util = {
    // 过滤指定字符的p标签
    filterPhtml: (html, filters) => {
        if (!html) {
            return html;
        }

        let $ = cheerio.load(html, {decodeEntities: false});

        _.each($('p'), (item) => {
            let ele = $(item);
            let phtml = ele.html();

            _.each(filters, ft => {
                if (phtml.indexOf(ft) >= 0) {
                    ele.remove();
                }
            });

        });

        html = $.html();
        $ = '';

        return html;
    },

    // 过滤 a标签连接和删除html标签中的script和link脚本
    filterAhtml: (html) => {
        if (!html) {
            return html;
        }

        let $ = cheerio.load(html, {decodeEntities: false});

        $('a:not(.a-anchor)').removeAttr('style').attr('href', 'javascript:void(0);').css({cursor: 'text'});// eslint-disable-line
        $('script,link').remove();

        html = $.html();
        $ = '';

        return html;
    },

    // 过滤 a标签连接和删除html标签中的script和link脚本
    imgAlt: (html, alt, num) => {
        if (!html) {
            return html;
        }

        let $ = cheerio.load(html, {decodeEntities: false});

        _.each($('img').slice(0, num), item => {
            let $dom = $(item);

            $dom.attr('alt', $dom.attr('alt') || alt);
        });

        html = $.html();
        $ = '';

        return html;
    }
};

module.exports = util;