【问题标题】:JavaScript match and replace; what is the best way?JavaScript 匹配和替换;什么是最好的方法?
【发布时间】:2011-05-27 07:21:30
【问题描述】:

所以我已经完成了这项工作,但我希望有人可以帮助我优化它。

我有大量的 XML 数据正在抓取并且无法控制。其中一个标签中有标记,而不是使用 >、

我只是想知道,我的 cleanFeedDescription() 函数能否做得更干净、更优化?

<script type="text/javascript">
        var textString = '&lt;img src=&quot;/media/filter/small/transfer/a0/46/21ca7da7/3569/1774/cf3f/82634fc4/img/4th_of_july_209.jpg&quot; alt=&quot;&quot; /&gt; &lt;p class=&quot;long-description&quot;&gt;&lt;span class=&quot;uploaded-date&quot;&gt;Uploaded 2010-11-29 18:24:24&lt;/span&gt;&lt;span class=&quot;uploaded-by&quot;&gt;by gin_alvizo&lt;/span&gt;&lt;span class=&quot;uploaded-to&quot;&gt;part of Bull&#039;s-Eye Bold BBQ powered by ...&lt;/span&gt;&lt;/p&gt;';

        document.write(cleanFeedDescription(textString));

        function cleanFeedDescription(descString) {

            descString = descString.replace(/&lt;/g, '<');
            descString = descString.replace(/&gt;/g, '>');
            descString = descString.replace(/&quot;/g, '"');

            return descString;
        };
    </script>

【问题讨论】:

    标签: javascript xml regex replace return


    【解决方案1】:

    我建议你只用一个函数替换一个函数而不是多个,这样会更快更容易维护。

    function cleanFeedDescription(descString) 
    {
        var replacements = { lt: '<', gt: '>', quot: '"' };
    
        return descString.replace(/&(\w+);/g, function(str, entity)
        {
            return replacements[entity] || "";
        });
    };
    

    【讨论】:

    • 这似乎是一个比连接一堆 .replace() 方法或使用臃肿的第三方脚本来获得我想要的结果更简单和更清洁的解决方案。谢谢! p.s.我需要修改你的正则表达式......在它的末尾添加了“g”! :)
    【解决方案2】:

    Here 是一个方便的 JS 库,为您完成 HTML 实体编码/解码,无需重新发明轮子。

    或者,如果您使用 jQuery,则有一个 similar question on SO 和一个以 jQuery 为中心的解决方案。

    【讨论】:

      【解决方案3】:

      好吧,您实际上并不需要将中间值分配给descString,因此您可以这样做...

      return descString.replace(/&lt;/g, '<')
                       .replace(/&gt;/g, '>')
                       .replace(/&quot;/g, '"');
      

      【讨论】:

        猜你喜欢
        • 2011-01-12
        • 1970-01-01
        • 2018-10-05
        • 1970-01-01
        • 2015-12-31
        • 2012-03-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多