You might want to check out the css white-space property. Setting the style to white-space: pre-wrap allows you to get rid of all that javascript, because it changes the behavior of whitespace to display instead of collapse.
And see this answer: HTML - Newline char in DIV content editable?