2

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

I have a ton of XML data 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>

3 Answers 3

2

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] || "";
    });
};
Sign up to request clarification or add additional context in comments.

1 Comment

This seems like a much more simple and cleaner solution than concatenating a bunch of .replace() methods or using bloated third party scripts to obtain my desired result. Thanks! p.s. I needed to modify your regExp... added "g" to the end of it! :)
2

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.

Comments

0

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, '"');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.