HTML - Newline char in DIV content editable?

Solution 1:

Set a style on the div: white-space: pre or white-space: pre-wrap

Example: http://jsfiddle.net/fPv6S/

Solution 2:

To add some info on @Explosion Pills correct answer and extract some info from MDN:

The CSS white-space attribute is there to help:

pre:

white-space: pre

Sequences of white space are preserved. Lines are only broken at newline characters in the source and at <br> elements.

This might result in unwanted horizontal scrollbars as shown in the example!

pre-wrap:

white-space: pre-wrap

Sequences of white space are preserved. Lines are broken at newline characters, at <br>, and as necessary to fill line boxes.

As @ceremcem pointed out the line breaks at the end of the box will not be transferred when the text is copy-pasted, which makes sense since these line breaks are not part of the text formatting but rather of the visual appearence.

pre-line:

white-space: pre-line

Sequences of white space are collapsed. Lines are broken at newline characters, at <br>, and as necessary to fill line boxes.

div{
  border: 1px solid #000;
    width:200px;
}
.pre {
    white-space: pre;
}
.pre-wrap{
   white-space: pre-wrap;
}
.pre-line{
   white-space: pre-line;
}

.inline-block{
    display:inline-block
}
<h2>
pre
</h2>
<div class="pre" contenteditable=true>Lorem ipsum dolor sit amet doesn't have a meaning but here comes 10 white spaces:____          ____</div>

<h2>
pre-wrap
</h2>
<div class="pre-wrap" contenteditable=true>Lorem ipsum dolor sit amet doesn't have a meaning but here comes 10 white spaces:____          ____</div>

<h2>
pre-line
</h2>
<div class="pre-line"  contenteditable=true>Lorem ipsum dolor sit amet doesn't have a meaning but here comes 10 white spaces:____          ____</div>

<h2>
Chrome FIX
</h2>
<div class="pre-line inline-block"  contenteditable=true>Lorem ipsum dolor sit amet doesn't have a meaning but here comes 10 white spaces:____          ____</div>

EDIT 08/14/2018:

In Chrome you might experience troubles: Pressing Enter will generate a new <div> inside your contenteditable. To prevent that you can either press Shift+Enter or set display: inline to the contenteditable <div> as seen in the fiddle.

Solution 3:

Try this......

var patt2 = new RegExp("<div>","g");
var patt3= new RegExp("</div>","g");
var patt4= new RegExp("<br>","g");
var z=x.replace(patt2,"\n").replace(patt3,"").replace(patt4,"");

That will do it...

Solution 4:

You could search and replace newlines with <br />. http://jsfiddle.net/fPv6S/1/