16

Hey all, I basically output content into a div like this using jquery:

var text = $("#edit").val();
$("#output").text(text);

But I want to turn "&lt;" and "&gt;" into "<" and ">".

text.replace(/&lt;/,"<"); doesn't seem to be working for me...

Any ideas? Many thanks

5
  • 1
    Could you use .html(text) instead of .text(text)? Commented Mar 14, 2011 at 17:23
  • 1
    Are you sure the problem isn't somewhere else? If I type in chrome console "abcde&lt;hey&gt;dfdfgf".replace(/&lt;/g,"<").replace(/&gt;/g,">") I get the correct answer... Commented Mar 14, 2011 at 17:25
  • @Peter: afraid not, I want "<" as TEXT not as html.. Commented Mar 14, 2011 at 17:27
  • mostly answered here: stackoverflow.com/questions/513112/… Commented Mar 14, 2011 at 17:40
  • I know. HTML interprets &lt; and &gt; as text. Commented Mar 14, 2011 at 17:58

4 Answers 4

27

Simple.

var needToConvert = 'But I want to turn "&lt;" and "&gt;" into "<" and ">".';

var convert = function(convert){
    return $("<span />", { html: convert }).text();
    //return document.createElement("span").innerText;
};

alert(convert(needToConvert));
Sign up to request clarification or add additional context in comments.

1 Comment

@mdlars Could you be more specific? I just tried it, and it still works.
27

You could use something like the unescapeHTML() function in prototype...

Adapted from prototype js source

function unescapeHTML(escapedHTML) {
  return escapedHTML.replace(/&lt;/g,'<').replace(/&gt;/g,'>').replace(/&amp;/g,'&');
}

Comments

0

assign it to variable:

var text = $("#edit").val();
text = text.replace("&lt;","<");

this will work fine

1 Comment

This will only replace the first occurrence, others are ignored
0

You need use .html() Because text() converts all html tags

$("#output").html(text);

Comments

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.