Strat-O
Strat-O

Reputation: 163

How can I convert strings with HTML entities into normalized form?

I want to use jquery to convert text containing strings like   
, etc into a more human-readable form. This works in jsfiddle:

<input id="stupid-approach" type="hidden">

function js_text(theVal) {
    $("#stupid-approach").html(theVal);
    x = $("#stupid-approach").html();
    return x;
}

alert(js_text("&eacute;"));

But I'm wondering if there is a way to do it that does not rely on a hidden field in the DOM?

Upvotes: 0

Views: 347

Answers (4)

dandavis
dandavis

Reputation: 16726

in consideration of the feedback about jQuery's .html() method's evaluation of script tags, here is a safer native version that's not tooo unwieldy:

function js_text(theVal) {
    var div=document.createElement("div");
    div.innerHTML=theVal;
   return div.textContent;
}

use it instead of $(xxx).html() when you don't trust the input 100%

Upvotes: 1

adeneo
adeneo

Reputation: 318202

just create an empty element, there's no need to have an actual hidden element in the DOM :

function js_text(theVal) {
    return $("<div />", {html: theVal}).text();
}

FIDDLE

Upvotes: 8

Tomas Kirda
Tomas Kirda

Reputation: 8413

You should be able to just do:

return $('<div>'+ theVal + '</div>').html();

Upvotes: 0

RichieHindle
RichieHindle

Reputation: 281485

No. There's no purely programmatic way to do this that doesn't involve getting the browser to treat the string as HTML, as in your example. (Beware untrusted inputs when doing that, by the way - it's an injection attack waiting to happen.)

Upvotes: 0

Related Questions