微信小程序-富文本轉(zhuǎn)文本

微信小程序-富文本轉(zhuǎn)文本

最近小程序這么火,我也來搞搞。發(fā)現(xiàn)了一個惡心的問題。小程序沒有組件能支持富文本內(nèi)容的,改接口又不太合適,于是有了這問,沒技術(shù)含量純粹記錄

首先我們看眼沒有被格式的富文本顯示:

*.wxml內(nèi)代碼。content是富文本內(nèi)容

    <view>
     <text>{{content}}</text>
    </view> 

顯示結(jié)果:

小程序無法解析html
小程序無法解析html

由以上圖片看到,小程序無法解析html文件

我們需要處理html富文本內(nèi)容,讓其顯示好看點

下面直接上代碼了,主要功能就是利用js的replace 對富文本經(jīng)行處理,大家可以看一下。一起優(yōu)化,方便對富文本更好的處理。

convertHtmlToText: function convertHtmlToText(inputText) {
    var returnText = "" + inputText;
    returnText = returnText.replace(/<\/div>/ig, '\r\n');
    returnText = returnText.replace(/<\/li>/ig, '\r\n');
    returnText = returnText.replace(/<li>/ig, '  *  ');
    returnText = returnText.replace(/<\/ul>/ig, '\r\n');
    //-- remove BR tags and replace them with line break
    returnText = returnText.replace(/<br\s*[\/]?>/gi, "\r\n");

    //-- remove P and A tags but preserve what's inside of them
    returnText=returnText.replace(/<p.*?>/gi, "\r\n");
    returnText=returnText.replace(/<a.*href="(.*?)".*>(.*?)<\/a>/gi, " $2 ($1)");

    //-- remove all inside SCRIPT and STYLE tags
    returnText=returnText.replace(/<script.*>[\w\W]{1,}(.*?)[\w\W]{1,}<\/script>/gi, "");
    returnText=returnText.replace(/<style.*>[\w\W]{1,}(.*?)[\w\W]{1,}<\/style>/gi, "");
    //-- remove all else
    returnText=returnText.replace(/<(?:.|\s)*?>/g, "");

    //-- get rid of more than 2 multiple line breaks:
    returnText=returnText.replace(/(?:(?:\r\n|\r|\n)\s*){2,}/gim, "\r\n\r\n");

    //-- get rid of more than 2 spaces:
    returnText = returnText.replace(/ +(?= )/g,'');

    //-- get rid of html-encoded characters:
    returnText=returnText.replace(/ /gi," ");
    returnText=returnText.replace(/&/gi,"&");
    returnText=returnText.replace(/"/gi,'"');
    returnText=returnText.replace(/</gi,'<');
    returnText=returnText.replace(/>/gi,'>');

   return returnText;
}

將上面代碼放入任意適合的小程序js文件中,
然后在需要處理數(shù)據(jù)的js文件里,引入文件,下面給出放入app.js文件中的調(diào)用示例:

var app = getApp()//獲取app小程序?qū)嵗? onLoad: function (options) {
       wx.request({
      url: 'http://example.com/api' + options.id+'.json',
      headers: {
        'Content-Type': 'application/json'
      },
      success: function (res) {
       res.data.content =  app.convertHtmlToText(res.data.content )
         that.setData({
           art: res.data.content
         })
         console.log(res.data)
      }
    })
}

然后編譯刷新下,可以看到結(jié)果了:

結(jié)果
結(jié)果

這里可以繼續(xù)調(diào)整下css,使顯示得更好看點。

要是有更好的方法還請留言

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容