Michael Schwartz
Michael Schwartz

Reputation: 8415

Remove New Line in Textarea and Replace with \n Character in Value

Fiddle - http://liveweave.com/YNegwI

I'm working on making a small little generator. However I ran into a problem I haven't figured out how to fix.

For example:

Say this is the code I want to convert

.editor, .preview {
  position: absolute;
  width: 50%;
  height: 100%;
  padding: 0;
  font-family: monospace;
  line-height: 1;
  min-height: 1.4em;
  line-height: 1.4em;
  font-size: 1em;
  border: 0;
  border-radius: 0;
  resize: none;
}

.editor {
  left: 0;
  color: #0b0;
  background-color: #000;
}

.preview {
  right: 0;
  background-color: #fff;
}

The final result should generate the following code.

body {\n  margin: 0;\n  background: #333;\n}\n\n.editor, .preview {\n  position: absolute;\n  width: 50%;\n  height: 100%;\n  padding: 0;\n  font-family: monospace;\n  line-height: 1;\n  min-height: 1.4em;\n  line-height: 1.4em;\n  font-size: 1em;\n  border: 0;\n  border-radius: 0;\n  resize: none;\n}\n\n.editor {\n  left: 0;\n  color: #0b0;\n  background-color: #000;\n}\n\n.preview {\n  right: 0;\n  background-color: #fff;\n} 

For those that don't quite understand the question: I'm removing each new line and trying to write \n NOT to insert a new line but to display the text of the code itself. As shown above.)

Upvotes: 0

Views: 1769

Answers (2)

YuS
YuS

Reputation: 2045

Because the \ means a start of some special character or command, you must escape it (by adding another one slash) to output "as is" and prevent it's processing: \\n

$(document).ready(function() {
  var editor = $('.editor'),
      preview = $('.preview');

  // Remove new line and insert new like "\n" to show the text in value
  editor.on('load keyup change', function() {
    preview.val( $(this).val().replace(/\n/g,'\\n') );
  }).change();
});

Upvotes: 2

leopik
leopik

Reputation: 2351

In the fiddle you have provided I would replace "break_meee_baby" with "\\n" (slash-slash-n). That seems to generate exactly what you need.

Upvotes: 3

Related Questions