Tuesday, 1 July 2014

Javascript: Convert text to HTML Number

I needed to display a JSON object on screen within a Tooltipster tooltip and I was pulling my hair out trying to figure out how to so it... Then I came across this lovely post. Shamelessly stealing the process I wrote my own as, for some reason, I prefer HTML Numbers rather than unicode:

function preJSON(json){
    var pre = "<pre>";
    var erp = "</pre>";
    var br = "<br />";
    var quote = '"';
    var space = " ";
    var jsonString = JSON.stringify(json, undefined, 2).replace(/"/g, toHTMLNumber(quote)).replace(/\n\r?/g, toHTMLNumber(br)).replace(/ /g, toHTMLNumber(space));
    return toHTMLNumber(pre) + jsonString + toHTMLNumber(erp);
    function toHTMLNumber(theString){
        var HTMLNumberString = '';
        for (var i=0; i < theString.length; i++) {
            var theHTMLNumber = theString.charCodeAt(i).toString(10).toUpperCase();
            theHTMLNumber = '&#' + theHTMLNumber + ';';
            HTMLNumberString += theHTMLNumber;
        }
        return HTMLNumberString;
    }
}

And then I call tooltipster with "contentAsHTML": true and it works a treat.