解决 uni-app 中富文本包含双引号无法渲染的问题

测试用富文本如下:

<p style="border: 0px; margin-top: 0.63em; margin-bottom: 1.8em; padding: 0px; counter-reset: list-1 0 list-2 0 list-3 0 list-4 0 list-5 0 list-6 0 list-7 0 list-8 0 list-9 0; color: rgb(25, 25, 25); font-family: "PingFang SC", Arial, 微软雅黑, 宋体, simsun, sans-serif; white-space: normal; background-color: rgb(255, 255, 255); text-align: justify;"><span style="border: 0px; margin: 0px; padding: 0px;">这是一段富文本</span></p>

使用 uni-app 的 rich-text 组件直接渲染会抛出 Vue 引擎解析的错误,原因是 font-family 的值里面包含了双引号,此时需要先处理下引号嵌套的问题再使用。

function formatQuoteInStyle(htmlString) {
    var stylePattern = /style="[^=>]*"[\s+\w+=|>]/g;
    var innerQuotePattern = /(?<!=)"(?!>)/g;
    return htmlString.replace(stylePattern, function(matches) {
        return matches.replace(innerQuotePattern, '\'');
    });
}

上述方法会将 style 属性值里面的双引号转换为单引号,这样就可以继续执行下去了。

posted @ 2020-10-03 14:36  月半流云  阅读(1633)  评论(2编辑  收藏  举报