2

It seems that escape sequences in JavaScript don't work? I'm writing in HTML 5 and am a fairly newbie. Single quote, double quote, and backslash DO work. But newline \n, backspace \b, carriage return \r, and tab \t don't work. Can anyone give me an idea why it's not? or a workaround?

<script type="text/javascript">
document.write("Hey bob!, \'You is da bomb!");
</script>

Thanks.

1

1 Answer 1

4

But newline \n, backspace \b, carriage return \r, and tab \t don't work.

Those characters are not treated in any special way in HTML, they are simply whitespaces. If you want to create a line break in HTML, you have to use the <br /> tag.

From the specification (emphasis mine):

This specification does not indicate the behavior, rendering or otherwise, of space characters other than those explicitly identified here as white space characters. For this reason, authors should use appropriate elements and styles to achieve visual formatting effects that involve white space, rather than space characters.


To be clear: This has nothing to do with JavaScript, only with how HTML works. Tiny example: Fiddle. I have a line break in my source code (that's the same as what would be created with document.write('Foo \n bar')), but the line break is not rendered in by the browser.

If you use alert or console.log instead of document.write you will see the actual generated string, because the string is not displayed in a HTML context.

Sign up to request clarification or add additional context in comments.

4 Comments

so 'when' does the above escape sequences work? If the file was a .js file would they work? I'd like to understand why if possible. Whitespace would be &nbsp; - so you're saying JavaScript ignores them in an HTML page? I thought when I'm coding between <script> tags that it is being interpreted as JavaScript - hence the \' and \\ and \" work fine even though HTML doesn't treat those any special way? Further clarification?
Sorry if I wasn't clear. Of course all those escape sequences "work". If you use document.write('Foo \n bar'), then you are inserting a character sequence with a line break into the HTML document. However, you won't be able to see the line break, because HTML doesn't recognize it. This has nothing to do with JavaScript, only with how HTML works. Tiny example: jsfiddle.net/Ah2J7. I have a line break in my source code (that's the same as what would be created with document.write('Foo \n bar')), but the line break is not rendered in by the browser.
If you use alert or console.log instead of document.write you will see the actual generated string, because the string is not displayed in a HTML context.
Interesting. Thank you for further explanation!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.