NewLine escape character not working

2019-01-20 00:16发布

问题:

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.

回答1:

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).


回答2:

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).



回答3:

use document.writeln() method .

The writeln() method is identical to the write() method, with the addition of writing a newline character after each statement.

try this

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