0

Is there a way to write text (and not decode special characters) using Javascript? I have tried document.write() but it appears to convert characters like & back to &, while JQuery's .text() keeps &.

My code

<script>document.write('&amp;');</script>

What it returns

&

What I want it to return

&amp;
ZomoXYZ
  • 1,415
  • 15
  • 40

3 Answers3

3

Just convert all the & to &amp; and it should work for you:

stringToBeWritten = "Hi&Hi - Hi&amp;Hi";
stringToBeWritten = stringToBeWritten.replace(/(&)/gi, "&amp;");
document.write(stringToBeWritten);

<script>
  stringToBeWritten = "Hi&Hi - Hi&amp;Hi";
  stringToBeWritten = stringToBeWritten.replace(/(&)/gi, "&amp;");
  document.write(stringToBeWritten);
</script>

ps: Don't use document.write() as it is not good. See Why is document.write considered a "bad practice"?

Solution 2

We can actually use the browser itself to make this happen.

function escapeStuff (unescaped) {
  DiV = document.createElement("div");
  DiV.innerText = unescaped;
  return DiV.innerHTML;
}
<input type="text" id="un" value="& <>" /> <input onclick="res.innerText = escapeStuff (un.value);" value="Escape it!" type="button" />
<div id="res"></div>
Community
  • 1
  • 1
Praveen Kumar Purushothaman
  • 154,660
  • 22
  • 177
  • 226
3

Actually, simply use element.textContent instead of document.write :)

For example, check this JSFiddle link or the code snippet below:

document.getElementById('myspan').textContent= 'Click &lt;HERE&gt;';
document.write('Click &lt;HERE&gt;');
With element.textContent: <span id="myspan"></span>
<br />
With document.write(): 

Update: replaced usage of innerText by textContent as suggested by Leon Adler in the comments.

ccjmne
  • 7,914
  • 3
  • 41
  • 56
0

There's a difference between html and text. You want to set text:

var myText = 'A &amp; B';

// Setting HTML: Result text will be "A & B"
document.write(myText);   // <- don't use document.write!
jQuery('#myElement').html(myText);
myElement.innerHTML = myText;

// Setting Text: Result text will be "A &amp; B"
document.write('A &amp; B'.replace(/&/g, '&amp;').replace(/</g, '&lt;'));   // <- don't use document.write!
jQuery('#myElement').text(myText);   // removes all children and sets the text of the element
myElement.textContent = myText;   // sets the text of the element
myElement.innerText = myText;   // removes all children and sets the text of the element

Note that document.write is usually a bad idea, since it only works when your page was not loaded completely, and using document.write later (like when clicking a button) will replace the entire content of your page.

I can also advise against using innerText. It is a non-standard property which was defined by Internet Explorer and later adapted by Chrome, but is not supported in Firefox (which is fine, seeing as it is not in the standards). You can use textContent instead.

Leon Adler
  • 2,330
  • 1
  • 21
  • 38