下面的這個方法是在百度上找的,但是老是報錯,一直沒找到原因,索性自己就挨個檢查了下,發現在過濾之前需要對傳過來的值進行檢測,是字符串才能讓這個方法執行
filters: { formatRichText(html) { //控制小程序中圖片大小 let newContent = '' newContent = html.replace(/<img[^>]*>/gi, function(match) { match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, ''); match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, ''); match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, ''); return match; }); newContent = newContent.replace(/style="[^"]+"/gi, function(match) { match = match.replace(/width:[^;]+;/gi, 'max-width:100%;').replace(/width:[^;]+;/gi, 'max-width:100%;'); return match; }); newContent = newContent.replace(/<br[^>]*\/>/gi, ''); newContent = newContent.replace(/\<img/gi, '<img style="max-width:100%;height:auto;display:inline-block;margin:10rpx auto;"'); return newContent; } },
以下為完整方法
filters: { formatRichText(html) { //控制小程序中圖片大小 let newContent = '' if (typeof(html) == 'string') { //檢測值為字符串才能進行replace操作 newContent = html.replace(/<img[^>]*>/gi, function(match) { match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, ''); match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, ''); match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, ''); return match; }); newContent = newContent.replace(/style="[^"]+"/gi, function(match) { match = match.replace(/width:[^;]+;/gi, 'max-width:100%;').replace(/width:[^;]+;/gi, 'max-width:100%;'); return match; }); newContent = newContent.replace(/<br[^>]*\/>/gi, ''); newContent = newContent.replace(/\<img/gi, '<img style="max-width:100%;height:auto;display:inline-block;margin:10rpx auto;"'); return newContent; } } },