html標簽反轉義


情景是這樣的(小程序或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顯示在頁面中呢?如下。

 

首先 在js中封裝好反轉義相關方法:

 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(/&amp;/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方法為標簽增加同名類名;

  &#39;要替換成單引號 '

 

1 this.activityBody = res.data.body;
2 this.activityBody.htmlContent = this.tools
3     .UnicodeToAscii(this.tools.escapeHtml(this.activityBody.content))
4     .replace(/&#39;/gi, "'")
5     .replace(/<p/gi, '<p class="_p"')
6     .replace(/ <img/gi, '<img class="_img"')
7     .replace(/<table/gi, '<table class="_table"');

 

最后 通過v-html在結構中使用轉義后的content:

1 <div class="content">
2     <h1> 標題 </h1>
3     <div class="line"><span>我是一條線</span></div>
4     <div v-html="Body.htmlContent"></div>
5 </div>

 

此處效果自行感受...


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM