Reputation: 1852
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('&');</script>
What it returns
&
What I want it to return
&
Upvotes: 0
Views: 145
Reputation: 9618
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 <HERE>';
document.write('Click <HERE>');
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.
Upvotes: 3
Reputation: 3331
There's a difference between html and text. You want to set text:
var myText = 'A & 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 & B"
document.write('A & B'.replace(/&/g, '&').replace(/</g, '<')); // <- 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.
Upvotes: 0
Reputation: 167172
Just convert all the &
to &
and it should work for you:
stringToBeWritten = "Hi&Hi - Hi&Hi";
stringToBeWritten = stringToBeWritten.replace(/(&)/gi, "&");
document.write(stringToBeWritten);
<script>
stringToBeWritten = "Hi&Hi - Hi&Hi";
stringToBeWritten = stringToBeWritten.replace(/(&)/gi, "&");
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>
Upvotes: 3