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.
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.
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.
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.
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.
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:
<br>
<p>...</p>
, etc.)<pre>...</pre>
element (or any element with the white-space: pre
, white-space: pre-wrap
, or white-space: pre-line
style applied to it).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
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With