How to add new line in string?

How to Add a New Line in a String [Solved]

String manipulation in JavaScript is one of those things that’s easy to learn but hard to master.
Once you think you have a grasp on it, a change of context can throw a wrench into everything you’ve learned up to that point.

If you’ve ever had trouble adding a new line character to a string, read on.
How to add a new line to a string

In JavaScript and many other programming languages, the newline character is \n. To add a new line to a string, all you need to do is add the \n character wherever you want a line break.

For example:

const testStr = "Hello, World,\nand all you beautiful people in it!

console.log(testStr);
/*
Hello, World,
and all you beautiful people in it!
*/

Be mindful of the white space around the newline character, as it may affect the characters after the line break:

const testStr = "Hello, World,\n and all you beautiful people in it!

console.log(testStr);
/*
Hello, World,
 and all you beautiful people in it! 
*/

With template literals, sometimes called template strings, that were introduced in ES6, it’s even easier to add new lines to your strings.

Template literals are just strings wrapped in backticks (`) rather than single (’) or double (") quotation marks.

One of the things that makes template literals really special is that they preserve any white space, including newlines:

const testStr = `Hello, World,
and all you beautiful people in it!`;

console.log(testStr);
/*
Hello, World,
and all you beautiful people in it!
*/

That’s all easy enough to understand, but what if you try to append your string with line breaks to a web page?

How to append a string with new lines to the DOM

Imagine you have the following code:

<div id="ovde">
  ...
</div>
div {
  font-size: 2em;
  font-weight: bold;
}
let customItems = "1,2,3";
customItems = customItems.split(",");

for (let i = 0; i < customItems.length; i++) {
  customItems[i] = "- " + customItems[i] + "\n";
}

customItems = customItems.join("");

document.getElementById("ovde").innerHTML = customItems;

It looks like your implementation should work.

You split the customItems string into an array of strings, then looped through and appended "- " to the beginning and "\n" to the end of each string in the array. Then you just used .join() to combine the array back into a single string and appended it to the DOM.

Here’s what it looks like with comments:

let customItems = "1,2,3";
customItems = customItems.split(",");

console.log(customItems); // ["1", "2", "3"]

for (let i = 0; i < customItems.length; i++) {
  customItems[i] = "- " + customItems[i] + "\n";
}

console.log(customItems); // ["- 1\n", "- 2\n", "- 3\n"]

customItems = customItems.join("");

console.log(customItems); // "- 1\n- 2\n- 3\n"

document.getElementById("ovde").innerHTML = customItems;

Still, when you look at the page, everything appears on the same line:

image-86
Even stranger, when you inspect the page, you can see the line breaks:


So what’s going on here?

Solution

There are a couple of things you can do depending on the situation.

Option 1

First, you could change your JavaScript code slightly and add linebreak (<br>) elements instead of "\n" after each string in the customItems array:

let customItems = "1,2,3";
customItems = customItems.split(",");

for (let i = 0; i < customItems.length; i++) {
  customItems[i] = "- " + customItems[i] + "<br>";
}

customItems = customItems.join("");

document.getElementById("ovde").innerHTML = customItems;

Which results in the following output:

image-88
Keep in mind that the <br> element has a very specialized purpose. According to MDN, <br> elements are only for adding line breaks in text “where the division of lines is significant” like a poem or a postal address.

Line break elements shouldn’t be used for breaking up paragraphs or increasing the spacing between elements. To do those, you should separate paragraph tags and adjust the margin in CSS to do both of those things, respectively.

Option 2

With that in mind, your second option is to adjust the CSS of the div element you’re appending the text to.

Go back to your original JS code:

let customItems = "1,2,3";
customItems = customItems.split(",");

for (let i = 0; i < customItems.length; i++) {
  customItems[i] = "- " + customItems[i] + "\n";
}

customItems = customItems.join("");

document.getElementById("ovde").innerHTML = customItems;

Then just add a new CSS declaration that sets the white-space property to no-wrap:

div {
  font-size: 2em;
  font-weight: bold;
  white-space: pre-wrap;
}

Which give you the same output as with option 1:

image-88
The white-space property adjusts how an element handles white space in its inner text. And the value no-wrap preserves the white space, including line breaks.

You can read more about the white-space property and its different values here: https://developer.mozilla.org/en-US/docs/Web/CSS/white-space

1 Like

You can add a new line in a string with "\n"

1 Like

take a look at jsfiddle

I stand corrected, go to the demo you have and inspect the elements. The new lines are there, the problem is how you put them in the DOM.

Since you use innerHTML you can use HTML < br /> for line breaks. If you want a line break in JS (for example if you use window.alert()) you use “\n”.

EDIT: Have a look at this stackoverflow question.

1 Like

I want to use \n for new line like i did on line 5.
In another case if i print “test\n\test” it goes to “test test”, i open dev tools and saw there is new line but how can i achieve this also in to be printed in “preview” of html, with new lines? i want to make list by adding "- " like prefix and “\n” like suffix so it goes to new line

By using < br /> it will continue on a new line. Or you can wrap your final customItems in between < pre > tags: document.getElementById("ovde").innerHTML = "<pre>" + customItems + "</pre>";

1 Like

here: [ https://codepen.io/ustvarno/pen/VjPQdY ]
it doesn’t work with "<pre>"
line 343, how can i make it so down below when i set items to div to get something like:
test1, test2, test3

->

-test1
-test2
-test3

EDIT: if u use dev tools, just click on blue button play if debbuger shows

That is strange, the code seems ok to me :confused:

The code does what it is supposed to do, the problem is that he tried to manipulate a string but did not return a string, instead made it an html element. The problem is with the html element he needs to find the right way, I’m not sure if he has tried the <br> or not but it was mentioned already.

This is what me and @BenGitter tried to get you to come up with: https://jsfiddle.net/x012yjk6/2/

That should normally work, but @nameToReachPeople is using React. I have no experience with React, so I won’t be able to help.

Well don’t feel bad, we answered the original question at least.

For the react part he should add it dynamically as in append it from the loop, but that is out of the scope of this question and I think should go into the react help category.

Take a look at https://github.com/markerikson/react-redux-links for learning react. I’m about to go dig in myself.

The link was from http://forum.freecodecamp.com/t/resources-for-learning-react-redux/672

2 Likes

Thanks all for help, sorry i didn’t mention it is react js, i was thinking it doesn’t matter

I achieve this with https://facebook.github.io/react/tips/dangerously-set-inner-html.html

1 Like

Try this:grinning:

1 Like