删除文本区域中的新行并替换为值中的字符

Remove New Line in Textarea and Replace with Character in Value

本文关键字:字符 替换 新行 文本 区域 删除      更新时间:2023-09-26

Fiddle-http://liveweave.com/YNegwI

我正在做一个小型发电机。然而,我遇到了一个问题,我还没想好如何解决。

例如:

假设这是我想要转换的代码

.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;
}

最终结果应该生成以下代码。

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} 

对于那些不太理解这个问题的人:我删除了每一行新行,并尝试编写'nNOT来插入新行,但显示代码本身的文本。如上所示。)

在您提供的小提琴中,我会将"break_meee_baby"替换为"''''n"(slash-slash-n)。这似乎正是你所需要的。

因为'意味着某个特殊字符或命令的开始,您必须对其进行转义(通过添加另一个斜线)以输出"原样"并阻止其处理:''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();
});