JavaScript match and replace; what is the best way?
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 = '<img src="/media/filter/small/transfer/a0/46/21ca7da7/3569/1774/cf3f/82634fc4/img/4th_of_july_209.jpg" alt="" /> <p class="long-description"><span class="uploaded-date">Uploaded 2010-11-29 18:24:24</span><span class="uploaded-by">by gin_alvizo</span><span class="uploaded-to">part of Bull's-Eye Bold BBQ powered by ...</span></p>';
document.write(cleanFeedDescription(textString));
function cleanFeedDescription(descString) {
descString = descString.replace(/</g, '<');
descString = descString.replace(/>/g, '>');
descString = descString.replace(/"/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(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"');
精彩评论