简体   繁体   中英

Outputting Escape Characters in JavaScript

I think it is a bit simple question but I couldn't find my answer neither on Stackoverflow nor Google. Here is my question. I want to output strings with escape characters. I have used the method document.getElementIdBy().

Here is my example

<!DOCTYPE html>
<html>
<head>
<title>JavaScript</title>
</head>
<body>
    <p id="example1"></p><br>
    <p id="example2"></p><br>
    <p id="example3"></p><br>
    <p id="example4"></p><br>
    <script>
        var x = "\"ABC\""
        var y = "\'ABC\'"
        var z = "ABC\nDEF"
        var t = "ABC\bDEF"
        document.getElementById("example1").innerHTML=x;
        document.getElementById("example2").innerHTML=y;
        document.getElementById("example3").innerHTML=z;
        document.getElementById("example4").innerHTML=t;
    </script>
</body>
</html>

The first two works fine. The third one doesn't create a new line and the fourth one doesn't crate a backspace. I assume that the variable z is like this

ABC
DEF

If I write this into ap element, it must show up like this: ABC DEF. Therefore I can understand why it doesn't appear as I expected (If I style the p element with white-space:pre it works as I expected)

However I wonder why \\b escape character doesn't work as expected. Actually I was expecting the output to be: ABDEF (without C). There may be some logic similar to the upper one but I cannot find. Can someone explain why it doesn't work?

I think these chars are just stripped from HTML, you could achieve what you want by replacing \\n with <br/>

eg

document.getElementById("example3").innerHTML=z.replace("\n","<br/>");

The third one doesn't create a new line

New lines in text are ignored in HTML tags. They are rendered as a space . Use <pre> tags to keep formatting:

<pre id="example3"></pre>

Or add <p> tags instead of new lines:

var z = "<p>ABC</p><p>DEF</p>"

Or <br>

var z = "ABC<br>DEF"

the fourth one doesn't crate a backspace

Do not pretty sure that HTML/JS supports \\b .

new line ( \\n ) doesn't generate new line in html.

so if you write:

<p>first line
second line</p>

you will get:first line second line.

so to write \\n to html you must convert it to <br> .

document.getElementById("example3").innerHTML=z.replace(/\n/g,'<br>');

this regular expression replaces all \\n with <br> .

and \\b is just character with code 8 . its special behavior occurs only when you send it to an input or text box.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM