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.
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).
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).
I made a much better solution. See it in action https://repl.it/#mamamia5x/Example
In css do
h1 span::before {
content: "\A";
white-space: pre;
}
Replace the h1 with whatever you have. Now, whenever you do <span>, a new line will break. So whenever someone says /n, it'll do the <span> and make a new line.
if (txt.charAt(i) == '/' && txt.charAt(i + 1) =='n'){
document.getElementById("text").innerHTML += " <span>";
i = i + 2;
}
Here is it in action https://repl.it/#mamamia5x/Example, and here is a project I am using it for https://live-stream.mamamia5x.repl.co/.
I also made it work with <br>. If you want to do that, you can do
if (txt.charAt(i) == '<' && txt.charAt(i + 1) == 'b' && txt.charAt(i + 2) == 'r' && txt.charAt(i + 3) == '>'){
You can also mix the two together, and it can allow /n and <br>.
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));
}
use <br> instead of \n
it relative to HTML
Related
I want to add a linebreak in Javascript, but \n is not working and nothing else I found so far is not working (like <br> or \n). Also, because of the programming I cannot use .appendChild.
for (i=getchilds();i<number;i++){
container.appendChild(document.createTextNode("\n" + "Pers. " + (i+1) + " \u00a0"));
var input = document.createElement("input");
input.type = "number";
container.appendChild(input);
}
I think you may be confusing whitespace with the representation of whitespace. In your case you're appending characters that represent white-space to a string that you intend to be displayed as a line-break. I assume you're then appending it to an element whose style is not set to display it as white-space.
There are four basic ways to fix this:
Use an ordered list. If you can, do this, since it will be both structural and semantic. Notice the link shows how to control the list-item text (controlling the start number is more challenging).
If the container-referenced element accommodates this, add white-space: pre to it's style. This will cause your line-breaks to come into view. It's best to do this with CSS, but you can do it with Javascript too.
Replace the \n with a <br>. Denys Séguret has an example of this.
Use a pre tag for the container-referenced element. <pre> automatically respects and displays line-breaks in content. This of course implies your content accommodates using a pre-formatted tag.
Change your code to insert into a textarea or a set of pre tags.
You might see your code injecting a single space in place of the line breaks in a plain text input of your browser is Firefox chrome or opera.
You can't insert \n in text node and have them correctly rendered in an element with standard white-space rendering.
Two solutions here:
insert <br> elements
container.appendChild(document.createElement("BR"));
container.appendChild(document.createTextNode("Pers. " + (i+1) + " \u00a0"));
use innerText in SPAN
var node = document.createElement("SPAN");
node.innerText = "\n Pers. " + (i+1) + " \u00a0";
container.appendChild(node);
The first one is the most relevant in your case, but the fact innerText doesn't remove newlines (contrary to textContent) is often useful.
I have this simple JavaScript:
function property() {
var ua = document.getElementById('greenBack').innerHTML;
var finals;
finals = ua;
if (ua.indexOf('p')) {
finals += '<br>\n Unknown Error';
}
return finals;
}
The problem is that I would like a newline to be shown when the function output is displayed in console.log() without the <br> tag (because <br> displays on the console) , but also be able to write the text "Unknown Error" to a newline in html without using <br>.
Is there any solution to display a newline in HTML and the console without \nor <br> ?
Just use \n for the console output. Then, when showing the text on a HTML page, you can either:
replace \n with <br>
or wrap a <pre> tag around it which will respect white-space and newlines
or use CSS-style white-space: pre-wrap; on any other HTML element
See this jsFiddle
$('#test').text('This\n is\n a\ntest');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre id="test"></pre>
You can print your information in a textarea. It will use the \n for the new line as the console
pre tag what you write it display all as it is including space, \n used for new line, br tag also to move to new line, some more option comes in handy when you use js literal represented as and found on key board between esc and tap button with sign ** `** variable can be put in side ${variable inside here}.
This is similar to other questions, but it's about something specific.
The first example doesn't do anything (breaks)
The second example works except that it hacks up html tags (specifically a tags) as well, so href="something with numbers" get hashed and then the whole thing falls apart
Then I get anchors that have their href attributes hashed up with span tags. Obviously that isn't what I want. What am I doing wrong? There must be some way to put all numbers and ", - : ()" inside a span without hashing up the html tags themselves.
$('#main-content p').contents().not("a").html(function(i, v) {
return v.replace( /([0-9(),-:]+)/g , '<span class="number">$1</span>');
});
$('#main-content p').html(function(i, v) {
return v.replace( /([0-9(),-:]+)/g , '<span class="number">$1</span>');
});
You are replacing all number. You need to only select the text nodes within the element. This code is not tested, but should work.
EDIT: You have to also call .contents(). See this answer
EDIT 2: I got it working in this FIDDLE. Let me know what you think. Did you mean to replace special characters as well as numbers?....because that is what is currently happening per your original regEx.
$('p').contents().filter(function () { return this.nodeType === 3; }).each(function(){
$(this).replaceWith($(this).text().replace( /([0-9(),-:]+)/g ,
'<span class="number">$1</span>'));
});
I am using this code to insert a new line in a content editable HTML document:
execCommand("insertHTML", false, '\n');
This works for me in Chrome and Safari, but it results in < br> or a new paragraph in other browsers. Because I am editing < pre> tags, I do not want the browser to change \n to a < br>. How can I do this?
I have already tried to use functions like range.insertNode() or to manipulate insertBrOnReturn in FireFox, but it is always the same. Isn't there a way to insert a \n in the document without the browser changing my input?
I think there is no cross-browser working way to add a \n... I am not THAT familiar with contenteditable but since it is changing the innerHTML you could maybe do something like
var currentContent = myContent; // "currentContent holds" the current content
execCommand("insertHTML", false, '\n'); // inserts the line break
if (newContent !== currentContent + '\n') { // "newContent" holds the content afterwards
console.log('use String.prototype.replace to replace created tag with "\n"');
}
I'm assuming that you want to save the edited content afterwards, so how about replacing all <br>s with \ns when getting the content of the tag? Just like this:
document.getElementById("editable").innerHTML.replace(/<br>/g, "\n");
edit: You may also just use the innerText instead of the innerHTML. When doing so, all newlines are presented as <br> tags (at least I got that result in Chrome). This solution isn't great, but it's at least always the same.
I have a variable in JavaScript that contains the contents of an html textarea. When I print the variable all that were entered by the user are forgotten. Is there any way to find the spaces in the string so I can separate each line?
here is a function , you can use for your script:
function nl2br (str) {
var breakTag = ''; return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1'+ breakTag +'$2');
}
HTML collapses adjacent whitespace - so if you are displaying within HTML, that's what you are seeing.
You can replace spaces with non break spaces: - this will ensure they are displayed in HTML and not collapsed.
Another option is to place them in a <pre> element
You mean all newlines? HTML ignores newlines and collapses whitespace by default. Print them inside a <pre> tag, or check out the CSS white-space property: http://www.w3schools.com/cssref/pr_text_white-space.asp
You can also replace newlines with <br> tags using:
while (str.indexOf("\n") > -1) str = str.replace("\n","<br>");