Skip to contentSkip to author details

Decoding HTML special characters using JavaScript regular expressions

 JavaScript regex Pebble HTML

I’ve been working with a web service that returns HTML encoded special characters. I have been working all morning on coming up with a regular expression to convert something like:

–

To its real-world equivalent:

I finally found a great JavaScript method to do this:

Decoding HTML Special Characters with JavaScript and regular expressions

Basically, it comes down to one function:

var decodeHtmlEntity = function(str) {  
    return str.replace(/&#(d+);/g, function(match, dec) { 
        return String.fromCharCode(dec); 
    }); 
};

Here is an alternative which I am using in my App:

function parseHtmlEntities(str) { 
return str.replace(/&#([0-9]{1,4});/gi, function(match, numStr) { var num = parseInt(numStr, 10); // read num as normal number return String.fromCharCode(num); }); }

There were other solutions out there to do this, but they depend on using the browser DOM. I’m trying to write code that runs on the Pebble smartwatch, so I can’t use the DOM. This solution works beautifully.