开发者

JavaScript match and replace; what is the best way?

开发者 https://www.devze.com 2023-01-30 23:30 出处:网络
So I\'ve already got this working but I\'m hoping someone can help me optimize it. I have a ton of XML da开发者_开发问答ta that I\'m grabbing and do not have control over. One of the tags has markup

So I've already got this working but I'm hoping someone can help me optimize it.

I have a ton of XML da开发者_开发问答ta that I'm grabbing and do not have control over. One of the tags has markup in it and instead of using >, < and " it uses the HTML names. I've setup a really simple function to return the string with the proper elements so that I can write it to the page.

I'm just wondering, can my cleanFeedDescription() function be done a little cleaner and more optimized?

<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>


I suggest you to use only one replace with a function instead of many, this will be faster and easier to maintain.

function cleanFeedDescription(descString) 
{
    var replacements = { lt: '<', gt: '>', quot: '"' };

    return descString.replace(/&(\w+);/g, function(str, entity)
    {
        return replacements[entity] || "";
    });
};


Here is a handy JS library that does the HTML entity encoding/decoding for you, no need to reinvent the wheel.

Alternately, if you're using jQuery, there's a similar question on SO with a jQuery-centric solution.


Well you don't really need to assign intermediate values to descString, so you could do it like this...

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

精彩评论

暂无评论...
验证码 换一张
取 消