Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert newline into javascript string

I have read this question/answer and this one, but I can't get it to work in my situation.

I'm building a list of names from a json array returned from a php script. After the below code I'm putting the goTosList string into a label via jquery. I need each name to be on a new line.

The below code is just outputting

var goTosList = '';
if (data !== 'empty') {
    // Build the go tos list as a comma-separated string
    $.each(data, function(index,element) {
        goTosList += (element['name'] === undefined ? '' : element['name']) + '\n\r';
    });
}

I've tried just \r and just \n and without the single quotes. I can't get it to work.

like image 989
marky Avatar asked May 28 '13 13:05

marky


People also ask

How do you add a newline to a string?

Adding Newline Characters in a String In Windows, a new line is denoted using “\r\n”, sometimes called a Carriage Return and Line Feed, or CRLF. Adding a new line in Java is as simple as including “\n” , “\r”, or “\r\n” at the end of our string.

What is the use of \n in JavaScript?

The \n character matches newline characters.

How do I add a new line to a string in HTML?

The <br> HTML element produces a line break in text (carriage-return).

How do you use BR in JavaScript?

To create a line break in JavaScript, use “<br>”. With this, we can add more than one line break also.


1 Answers

If you are output is HTML and you want newlines you have two options:

Either use a <pre> tag as a wrapper to your text (not suitable here I think)

<pre>some Text

with newlines</pre>

or add <br> instead of \n\r:

some Text<br>with newlines

So in your code this would translate to

goTosList += (element['name'] === undefined ? '' : element['name']) + '<br>';

and later on insert this into the DOM by

$('#yourLabel').html( goTosList );
like image 98
Sirko Avatar answered Sep 25 '22 16:09

Sirko