标签:ace reg nbsp col esc cape img his 结构
情景是这样的(小程序或vue下):
优惠活动的详情页是通过从数据库拿到数据动态生成的,数据库返回的页面结构数据content:
"<div class='cont-part'><div class='cont-title'></div><div class='cont-image'><img src='http://img.域名隐藏之术.cn/524/20191117170216250.png' ></div></div><div class='cont-part'><div class='cont-title'></div><div class='cont-image'><img src='http://img.域名隐藏之术.cn/524/20191117170216309.jpg' ></div></div><div class='cont-part'><div class='cont-title'></div><div class='cont-image'><img src='http://img.域名隐藏之术.cn/524/20191117170216335.png' ></div></div><div class='cont-part'><div class='cont-title'></div><div class='cont-image'><img src='http://img.域名隐藏之术.cn/524/20191117170217306.png' ></div></div>"
结构并不复杂,无非是标题、内容、图片三个部分,那么如何把这段数据转义成html显示在页面中呢?如下。
1 const escapeHtml = str => { // HTML 标签反转义 2 var arrEntities = { 3 ‘lt‘: ‘<‘, 4 ‘gt‘: ‘>‘, 5 ‘nbsp‘: ‘ ‘, 6 ‘amp‘: ‘&‘, 7 ‘quot‘: ‘"‘, 8 }; 9 return str.replace( /&(lt|gt|nbsp|amp|quot);/ig, function ( all, t ) { 10 return arrEntities[ t ]; 11 } ); 12 } 13 14 const UnicodeToAscii = ( content ) => { // Unicode 转换 ASCII 15 let contentCopy = content.replace(/&/ig,‘&‘); 16 let code = contentCopy.match( /&#(\d+);/g ), 17 result = ‘‘; 18 if ( code && code.length > 0 ) { 19 for ( var i = 0; i < code.length; i++ ) { 20 let asciiStr = String.fromCharCode( code[ i ].replace( /[&#;]/g, ‘‘ ) ); 21 result = contentCopy.replace( new RegExp( code[ i ], ‘g‘ ), asciiStr ); 22 } 23 return result; 24 } else { 25 return contentCopy; 26 } 27 }
由于uniapp中不支持div、p、img等标签,所以要用到replace方法为标签增加同名类名;
'要替换成单引号 ‘
1 this.activityBody = res.data.body; 2 this.activityBody.htmlContent = this.tools 3 .UnicodeToAscii(this.tools.escapeHtml(this.activityBody.content)) 4 .replace(/'/gi, "‘") 5 .replace(/<p/gi, ‘<p class="_p"‘) 6 .replace(/ <img/gi, ‘<img class="_img"‘) 7 .replace(/<table/gi, ‘<table class="_table"‘);
1 <div class="content"> 2 <h1> 标题 </h1> 3 <div class="line"><span>我是一条线</span></div> 4 <div v-html="Body.htmlContent"></div> 5 </div>
此处效果自行感受...
标签:ace reg nbsp col esc cape img his 结构
原文地址:https://www.cnblogs.com/cnlisiyiii-stu/p/11969803.html