Javascript 如何从textarea(如堆栈溢出)进行问题预览

Javascript 如何从textarea(如堆栈溢出)进行问题预览,javascript,jquery,html,ecmascript-6,Javascript,Jquery,Html,Ecmascript 6,我有一个类似于我现在写的表格: <form> <div class="form-group"> <label for="body">Body</label> <textarea name="body" id="body" cols="30" rows="10" class="form-control" placeholder="Your question body here"></textarea>

我有一个类似于我现在写的表格:

<form>
  <div class="form-group">
      <label for="body">Body</label>
      <textarea name="body" id="body" cols="30" rows="10" class="form-control" placeholder="Your question body here"></textarea>
   </div>
</form>

身体
我有一个显示文本区域预览的html块:

<div class="question-preview border-top border-bottom pt-3 pb-3" id="question-preview">
<!--  <p>Default text question</p> -->
<!--  <pre class="prettyprint">var a = 5</pre> -->
 </div>

如何从textarea#body到div#问题预览实时生成html?预览块中的注释是默认文本和代码换行的示例。我不明白如何从代码中识别默认文本。我想我可以通过4个空格来区分它,但我的代码不起作用,我正在尝试这样的方法:

bodyTextarea.addEventListener('keyup', function (e) {
       e.preventDefault();
       const lines = this.value.split(/\n/);

       let code = lines
            .filter((line) => {
                if (/\s{4}/.test(line)) {
                    return line;
                 }
             })
             .reduce((accumulator, current) => {
                 return accumulator + current;
              }, '');

         // FIXME
        if (!/\s{4}/.test(lines[lines.length - 1])) {
             if (previewQuestionArea.querySelector('p')) {
                    previewQuestionArea.querySelector('p').replaceWith(`<p>${lines[lines.length - 1]}</p>`);
             } else {
                 previewQuestionArea.innerHTML = `<p>${lines[lines.length - 1]}</p>`;
               }
             } else {
                if (code !== '') {
                    previewQuestionArea.innerHTML += `<pre class="prettyprint">${code}</pre>`;
                }
            }
        });
bodyTextarea.addEventListener('keyup',函数(e){
e、 预防默认值();
常量行=此.value.split(/\n/);
让代码=行
.filter((行)=>{
如果(/\s{4}/.test(行)){
回流线;
}
})
.减少((蓄能器,电流)=>{
返回蓄能器+电流;
}, '');
//修理工
if(!/\s{4}/.test(lines[lines.length-1])){
if(previewQuestionArea.querySelector('p')){
previewQuestionArea.querySelector('p')。替换为(`${lines[lines.length-1]}

`); }否则{ previewQuestionArea.innerHTML=`${lines[lines.length-1]}

`; } }否则{ 如果(代码!=''){ previewQuestionArea.innerHTML+=`${code}`; } } });

有什么想法吗?

使用jQuery,我们可以定义一个正则表达式模式,并在找到匹配项时对代码应用特定的样式。在本例中,我希望使用3个引号作为分隔符:“”

对于语法高级用法,最好选择highlight.js或Google Prettify之类的库

$('textarea').bind('keyup change',function()){
var oldHtml=$(this.val();
var newHtml=oldHtml.replace(/“”(.*?“)”/g,“$1”);
$(“.question preview”).empty().html(newHtml);
});
。突出显示{
颜色:#B0BF1A;
背景色:#000;
}

身体