html标签反转义

在使用uni-app开发小程序时,后台返回的数据 如下:

<div class='cont-part'><div class='cont-title'></div><div class='cont-editor'><p>*****************;</p><p>***Magic English*********、******;</p><p>********;</p><p>******************;</p><p>***************;</p><p>***************。</p></div></div>

那么如何将这段数据转义成html显示在页面中呢?如下

首先 在js中封装好反转义相关方法:

const escapeHtml = str => { // HTML 标签反转义
    var arrEntities = {
        'lt': '<',
        'gt': '>',
        'nbsp': ' ',
        'amp': '&',
        'quot': '"',
    };
    return str.replace( /&(lt|gt|nbsp|amp|quot);/ig, function ( all, t ) {
        return arrEntities[ t ];
    } );
}

const UnicodeToAscii = ( content ) => { // Unicode 转换 ASCII
    let contentCopy = content.replace(/&/ig,'&');
    let code = contentCopy.match( /&#(d+);/g ),
        result = '';
    if ( code && code.length > 0 ) {
        for ( var i = 0; i < code.length; i++ ) {
            let asciiStr = String.fromCharCode( code[ i ].replace( /[&#;]/g, '' ) );
            result = contentCopy.replace( new RegExp( code[ i ], 'g' ), asciiStr );
        }
        return result;
    } else {
        return contentCopy;
    }
}
module.exports = {escapeHtml,UnicodeToAscii} //导出方法

然后 在main.js中全局引入 挂载:

// 引入js
import tools from "./common/js/util";

// 挂载原型
Vue.prototype.tools = tools;

然后 在接口返回数据的地方调用方法:

由于uni-app中不支持div、p、img等标签,所以要用到replace方法为标签增加同名类名;

&#39;要替换成单引号 '

    let thList = [];
        thList = res.data.data;
        for(let i = 0; i < thList.length; i++){
           thList[i].content = _this.tools
                .UnicodeToAscii(_this.tools.escapeHtml(thList[i].content))
                .replace(/'/gi, "'")
                .replace(/<p/gi, '<p class="_p"')
                .replace(/ <img/gi, '<img class="_img"')
                .replace(/<table/gi, '<table class="_table"');
            }
       _this.teacherList = thList;

最后 通过v-html在结构中使用转义后的content:

// 内容
<view v-html="item.content"></view>
原文地址:https://www.cnblogs.com/nljy/p/14362743.html