【问题标题】:Replacing HTML String & Avoiding Tags (regex)替换 HTML 字符串和避免标签(正则表达式)
【发布时间】:2013-05-17 08:29:10
【问题描述】:

我正在尝试使用 JS 替换包含 html 标签+属性和样式的字符串中的特定字符串,同时避免读取或匹配标签的内侧(并将原始标签保留在文本中)。

例如,当关键字为“pan”时,我希望<span> this is span text </span> 变为:<span> this is s<span class="found">pan</span> text </span>

我尝试使用正则表达式与.. 到目前为止我的正则表达式:

$(this).html($(this).html().replace(new RegExp("([^<\"][a-zA-Z0-9\"'\=;:]*)(" + search + ")([a-zA-Z0-9\"'\=;:]*[^>\"])", 'ig'), "$1<span class='found'>$2</span>$3"));

这个正则表达式只有在&lt;span class="myclass"&gt; span text &lt;/span&gt;这样的情况下才会失败,当搜索=“p”时,结果:

<s<span class="found">p</span>an class="myclass"> s<span class="found">p</span>an text</s<span class="found">p</span>an>

*本主题应该可以帮助任何寻求匹配并替换匹配字符串同时避免被特定字符包围的字符串被替换的人。

【问题讨论】:

    标签: javascript html regex string tags


    【解决方案1】:

    正如 thg435 所说,处理 html 内容的好方法是使用 DOM。

    但如果你想在替换中避免某些东西,你可以先匹配你想避免的东西,然后自己替换它。

    避免html标签的例子:

    var text = '<span class="myclass"> span text </span>';
    
    function callback(p1, p2) {
        return ((p2==undefined)||p2=='')?p1:'<span class="found">'+p1+'</span>';
    }
    
    var result = text.replace(/<[^>]+>|(p)/g, callback);
    
    alert(result);
    

    【讨论】:

    • 我推荐这种方法,因为它没有大循环,所以速度更快.. 非常感谢
    • 也许,但是请记住,回调函数在每次出现时都会被调用
    • 哎呀;这种方法与 chrome 有问题,它错误地执行了正则表达式,它也替换了空格和其他标签
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-20
    • 1970-01-01
    • 2019-04-17
    • 1970-01-01
    • 2018-07-13
    相关资源
    最近更新 更多