Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

looking at the replace chains on s(val) reminded me of something a while back, is there a faster/better way to do this king of stuff? something like:

return s(val).replace(re, function(t){

    if( t == '>' ) return '&gt';
    if( t == '<' ) return '&lt;';
    if( t == '&' ) return '&amp;';
    if( t == '"' ) return '&quot;';
    return t;
});


This isn't for the whole thing, but a common pattern to clean up that inner part could be something like:

    return { '>': '&gt;', '<': '&lt;', '&': '&amp', '"': '&quot;' }[t] || t
All formatted nicer than that, of course ;-)


    new Option("<div>in the browser, yes.</div>").innerHTML


Oh I like this. I was messing with a similar tactic appending a textNode to an HTML element but this is much more elegant.


The text node approach is cross-browser, whereas I don't think this works on oldIE.


I just tried this and it doesn't seem to escape " to &quot;.


yes! awesome snippit :)


You can make it 50% faster by observing that replacing > is unnecessary, and only one of < or " needs replacing in any particular context.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: