views:

2958

answers:

3

So I know I can write my own HTML-encoding function like this:

function getHTMLEncode(t) {
    return t.toString().replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;");
}

But I was wondering if there were any native facility for this that is available to XPCOM components. I'm writing a component, not an overlay, so I don't have a DOM around to do tricks like creating a DOM element and setting its innerHTML.

A: 
function encode2HTML(str) {
    var b = document.createElement('b');
    if (b.innerText === undefined) {
        b.textContent = str;
    } else {
        b.innerText = str;
    }
    return b.innerHTML;
}

The browser should know how to encode your text. Please test this before using. :)

Linas
Sorry, my mistake; did not read the question thoroughly...
Linas
A: 

In theory you could create an XML document, use that to create an HTML div, set its text content to your unencoded string and read off its innerHTML. Note that this only encodes lt, gt and amp characters, not quot.

Neil
+1  A: 

The answer appears to be no - there is no built in function in Firefox to HTML-encode a string from an XPCOM component.

BRH