美文网首页
正则表达式实现替换富文本中的某个内容

正则表达式实现替换富文本中的某个内容

作者: 变量只提升声明不提升赋值 | 来源:发表于2021-04-22 10:02 被阅读0次
this.html.replace(/\<img/gi, '<img style="max-width:100%;display:block" ')


全能替换
function replace_Rich_text (html) {
    let newContent = html.replace(/<img[^>]*>/gi, function(match, capture) {
        match = match.replace(/style\s*?=\s*?([‘"])[\s\S]*?\1/, '').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, capture) {
        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:block;margin-top:0;margin-bottom:0;"');
    return newContent;
}
通过字符串replace方法,第一个参数是正则表达式,找到想要替换的字符,第二个参数传入替换的内容

相关文章

  • 正则表达式实现替换富文本中的某个内容

  • 正则表达式

    正则表达式用来检索,替换符合某个规则的文本 正则表达式的方法 正则的匹配规则:

  • PHP七天系列之正则表达式

    正则表达式 正则表达式被用来检索或替换那些符合某个模式的文本内容。许多程序设计语言都支持利用正则表达式进行字符串操...

  • 正则表达式小记

    正则表达式通常被用来检索、替换那些符合某个模式(规则)的文本。现阶段很多语言有正则的实现,比如java,pytho...

  • iOS 修改超链接的富文本样式

    原理就是遍历富文本中带有超链接标识的文本,替换掉他们本来的富文本样式。

  • C# 正则表达式基础

    正则表达式 Regex类 元字符 正则表达式通常用来检查,检索,替换符合某个格式的文本 元字符: 正则表达式语言由...

  • Python学习笔记十五(正则表达式)

    正则表达式 什么是正则表达式 正则表达式,又称规则表达式。通常被用来检索、替换那些符合某个规则的文本。 Pytho...

  • sed+正则表达式 替换文本文件

    使用sed + 正则表达式批量匹配并替换文本内容 创建文件 text.txt 替换 「world」为 Moto 替...

  • Linux sed命令使用实例

      sed是Linux下一款功能强大的文本处理工具,可以替换、删除、追加文件内容,支持正则表达式使用。 文本替换将...

  • 正则表达式

    正则表达式 正则表达式,又称规则表达式,通常被用来检索、替换那些符合某个模式(规则)的文本。 正则表达式是对字符串...

网友评论

      本文标题:正则表达式实现替换富文本中的某个内容

      本文链接:https://www.haomeiwen.com/subject/ktsxrltx.html