• 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>
  • 相关阅读:
    [微软官方]SQLSERVER的兼容级别
    使用 OPENJSON 分析和转换 JSON 数据 (SQL Server)
    WPF 解决TreeViewItem上为IsMouseOver 时 父级Item也会 受影响
    依赖注入
    关于编译告警 C4819 的完整解决方案
    你想知道的 std::vector::push_back 和 std::vector::emplace_back
    如何使用 Dump 文件?
    关于 PDB 文件你需要知道什么?
    图解哈希表及其原理
    C++ 中的虚函数表及虚函数执行原理
  • 原文地址:https://www.cnblogs.com/nljy/p/14362743.html
Copyright © 2020-2023  润新知