Reputation: 51
For example;
var text = document.getElementById("escape").innerHTML;
alert(text);
text = "hello my name is \n cool";
alert(text);
<p id="escape">hello my name is \n cool</p>
During the first alert the text inside alert is displayed as
hello my name is \n cool
but in the second it becomes
hello my name is
cool
How can I get the first alert to be displayed as the second one?
Upvotes: 2
Views: 788
Reputation: 101768
What you're asking about is how to interpret a string value as a JavaScript string literal. The way to interpret a string as JavaScript is (the evil) eval
, which you can use here if you're careful enough:
function interpretJSString(value) {
return value
.split('"')
.map(function (v) {
return eval('"' + v + '"');
})
.join('"');
}
var text = document.getElementById("escape").innerHTML;
var interpretedText = interpretJSString(text);
alert(interpretedText);
<p id="escape">hello my "name" is \n \tcool</p>
The only escape sequence this will not handle is \"
, because it takes extra precautions to prevent any "
s in the value from breaking out of the string and causing havoc.
Upvotes: 0
Reputation: 179264
A string containing 'is \n cool'
in JavaScript can be represented as a list of characters:
["i", "s", " ", "↵", " ", "c", "o", "o", "l"]
^^^ newline character
Note how even though the string appears to contain backslash and n
characters, the actual value of the string does not. This is because \n
is an escape sequence that is evaluated as a single newline character.
Reading the text content of HTML that contains the literal text is \n cool
you will end up with a string that can be represented as a list of characters:
["i", "s", " ", "\", "n", " ", "c", "o", "o", "l"]
^^^ ^^^
| +- n character
+------ backslash character
Note how the string contains backslash and n
characters here. \n
is not an escape sequence in HTML, so the characters retain their values.
If you want HTML to contain the same value as the JavaScript string you need to include the same newline character properly encoded as HTML.
This can be done via a literal newline character:
<div>is
cool</div>
or can be done by using an HTML encoded newline character:
<div>is cool</div>
Note how even though the string appears to contain &
, #
, 1
, 0
, and ;
characters, the actual value of the string does not. This is because
is an HTML entity that is evaluated as a single newline character.
Upvotes: 1
Reputation: 349
Should use textarea instead and don't use \n, just hit enter to create a new line.
<textarea id="escape">
hello my name is
cool
</textarea>
Because the p or div tag will return raw string and the \ will be escaped as \\
Upvotes: 2