html标签反转义

您所在的位置:网站首页 js反转义html标签 html标签反转义

html标签反转义

2024-07-15 08:38| 来源: 网络整理| 查看: 265

在使用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': '', '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方法为标签增加同名类名;

'要替换成单引号 '

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(/


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3