0

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?

0

4 Answers 4

8

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

Sign up to request clarification or add additional context in comments.

3 Comments

@Poni the comma on the first line makes the var apply to x as well
@JanDvorak the original answer didn't have a comma, :p simple typo
I added the comma later, and changed it now to not need a comma !
1

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%

Comments

0

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.)

3 Comments

how is it an "injection attack waiting to happen"? an injection of CSS?
Script injection. What if the text in question is <script>do_harmful_stuff()</script>?
so what? nothing happens: .innerHTML-added scripts don't fire, and they never have... ED: ok, touchè. jQuery is TOO helpful here, one reason i don't like it...
0

You should be able to just do:

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

2 Comments

I made a minimum version of this function js_text(theVal) { return $("<div />").html(theVal).html(); } alert(js_text("&eacute;"));
function js_text(theVal) { return $(theVal.big()).html(); } is shorter... :P

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.