读取数据库的内容时突然跳出"、
、 "这些HTML标签、字符,吓一跳;本来如果是写HTML、JS倒也没什么,但是写小程序事时,小程序中是没有这些html标签的
第一种方法:只能处理简单的HTML标签,img解释不了,连“ ;”也处理不了,好处就只有一方法 代码少,无须引入文件。
在 app.js 添加以下方法代码,作为公共方法,所有页面都可用
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 文件里调用方法
var app = getApp() var content = app.convertHtmlToText(res.data.data.content);
**
在小程序中体验效果
微信小程序搜:红旗头像制作