Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NewLine escape character not working

We know that \n is used to feed a new line in JavaScript.
How should I use it for an output (in a for-loop):

str=prompt("Enter any string!");
    for(i=0;i<str.length;i++)
    {
        document.write('\n'+str.charCodeAt(i));
    }   

or

str=prompt("Enter any string!");
    for(i=0;i<str.length;i++)
    {
        document.write('\n'+str.charCodeAt(i));
    }

Neither seems to work.

like image 981
pop stack Avatar asked Apr 19 '12 10:04

pop stack


People also ask

What is the escape character for a newline Python?

In Python strings, the backslash "\" is a special character, also called the "escape" character. It is used in representing certain whitespace characters: "\t" is a tab, "\n" is a newline, and "\r" is a carriage return.

Why N does not work in JavaScript?

When you're using document. write, because it's writing to the document as HTML, a new line should be <br/> instead of \n. Your question is not clear but if you mean why "\n" is not visible as text in js then it is because it is newline character i.e it can be used to get an similar effect as html <br> tag.

How do you escape a newline character?

A commonly used escape sequence is \n, which inserts a newline character into a string. The string “This is line one, This is line two.” is displayed or printed on a single line.

Does \n work in JavaScript?

The newline character is \n in JavaScript and many other languages. All you need to do is add \n character whenever you require a line break to add a new line to a string.


2 Answers

This has nothing to do with JavaScript. In HTML, all whitespace (including newlines) is collapsed and treated as a single space.

To do a line break in HTML:

  • Use <br>
  • Or organize your text into paragraphs with <p>...</p>, etc.)
  • Or if you're outputting some form of formatted text (like code), you can do that in a <pre>...</pre> element (or any element with the white-space: pre, white-space: pre-wrap, or white-space: pre-line style applied to it).
like image 137
T.J. Crowder Avatar answered Sep 30 '22 15:09

T.J. Crowder


If you're writing to the document you'll want document.write('<br/>'+str.charCodeAt(i)); - or to set your output in a <pre> tag (or another element with the a style attribute of white-space:pre).

like image 33
Mikey Avatar answered Sep 30 '22 16:09

Mikey