Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/387.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript .replace()的换行符不';无法使用内容可编辑项_Javascript_Replace - Fatal编程技术网

Javascript .replace()的换行符不';无法使用内容可编辑项

Javascript .replace()的换行符不';无法使用内容可编辑项,javascript,replace,Javascript,Replace,我有一个简单的代码: <div style="margin-left:10px;"> <p> <a class="btn" href="#" onclick="myFunction()"><i class="icon-link"></i></a> </p> </div> <div style="margin-left:10px;"> <

我有一个简单的代码:

 <div style="margin-left:10px;">
    <p>
     <a class="btn" href="#" onclick="myFunction()"><i class="icon-link"></i></a>
    </p>
  </div>

  <div style="margin-left:10px;">

    <div id="example-one" >
      <p id="textEditor" contenteditable="true"></p>
    </div> 

  </div>



 <script type="text/javascript">



function myFunction()
{

  // removes <div> from #textEdtor's content
  $("#textEditor>div").replaceWith(function() { return $(this).contents(); }); 

  var str=document.getElementById("textEditor").innerHTML; 

  var n=str.replace(/\n|\r/g, '<br>')

  document.getElementById("textEditor").innerHTML=n;

  alert(n);
}

</script>


函数myFunction() { //从#textEdtor的内容中删除 $(“#textEditor>div”).replaceWith(函数(){return$(this.contents();}); var str=document.getElementById(“textEditor”).innerHTML; var n=str.replace(/\n |\r/g,
) document.getElementById(“textEditor”).innerHTML=n; 警报(n); }
问题是当用户按enter键时,
var n=str.replace(/\n |\r/g,
不起作用。虽然如果我使用这个
,它工作得很好。replace(/\[b\]/g',)。replace(/\[\/b\]/g',)

只有按两次enter键,它才会添加一个

有没有办法解决这个问题


谢谢。

问题在于删除子
元素。用下面的代码替换您的代码,一切都会正常工作:

function myFunction() {
    $("#textEditor > div").before("<br />").contents().unwrap();
}
函数myFunction(){
$(“#textEditor>div”)。在(“
”)之前。contents().unwrap(); }

演示:

如果您将str登录到控制台,是否有换行符
console.log(str)
并查看它是否是多行的。如果是这样,把它放到文本编辑器或在线JS正则表达式编辑器中,并开始在那里使用它。不过,如果没有一个有效的例子,很难说。请考虑在JSFIDel.NET<代码> CordeNeabd插入>代码> BR> < /代码>。你想做什么?@ExplosionPills它插入
块,但不插入

标记。@Eli Gassert它在控制台中返回相同的内容。