0

We have $str = " hello";

What's the best way to get $newstr equal to  hello; and so on to be sure it is displayed on the page the same way using jQuery?

2
  • Why not just replace the ampersand: $str = $str.replace(/&/, '&');? Commented Sep 26, 2014 at 16:44
  • The reason is it is not only &, but <> as well. "<div style='display:none;'>not visible text</div>" will show nothing on the page, not this string. Commented Sep 26, 2014 at 16:46

2 Answers 2

3

I think both answers by Matt Schmiermund and Alex Gidan are directing you to the right place.

You should try something like this :

var a = "<div>Your HTML & More</div>";
var span = document.createElement("span");
$(span).text(a)
$(span).html()

this will return the following :

"&lt;div&gt;Your HTML &amp; More&lt;/div&gt;"
Sign up to request clarification or add additional context in comments.

Comments

2

If you have to do it with JQuery (directly from your JS) you can use .text() / .html() functions:

 $('<div/>').text(value).html();


 $('<div/>').html(value).text();

2 Comments

Untoftunately, I'm not attaching it to div.
you can pick up the element you want to convert (even <body> for instance)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.