gal007
gal007

Reputation: 7202

How can I change the encoding/charset of a string on Javascript?

I'm getting some text from a div, like this:

var scriptContent = document.getElementsByTagName("pre")[0].innerHTML;

But if the text contains some like "X is < than Y" the scriptContent var will contain "X is &lt than Y". I really need to get exactly the same string I am seeing in the browser, that is "X is < than Y".

How can I solve this?

Upvotes: 0

Views: 1253

Answers (2)

Teemu
Teemu

Reputation: 23416

Use textContent property instead of innerHTML:

var pre = document.getElementsByTagName("pre")[0],
    scriptContent = pre.textContent || pre.innerText;

A live demo at jsFiddle. An alternative innerText is for IE<9.

Upvotes: 1

JohnJohnGa
JohnJohnGa

Reputation: 15685

From https://developer.mozilla.org/en-US/docs/Web/API/element.innerHTML

Note: If a , , or node has a child text node that includes the characters (&), (<), or (>), innerHTML returns these characters as &amp, &lt and &gt respectively. Use Node.textContent to get a correct copy of these text nodes' contents.

document.getElementsByTagName("pre")[0].textContent;

See: https://developer.mozilla.org/en-US/docs/Web/API/Node.textContent

Upvotes: 2

Related Questions