首页 > 解决方案 > 正确拆分文本区域值 jQuery 正则表达式

问题描述

我在正确拆分 textarea 值时遇到问题。我当前的代码片段拆分了以“-”开头的每一行并将其显示为 span 元素的值,但是,它不会收集不以“-”开头的下一行值。

例如,如果我将此文本粘贴到 textarea 中:

- first match 
rest of first match
- second match
- third match

脚本应输出:

<span style="color:red;">- first match rest of first match </span><br>
<span style="color:red;">- second match</span><br>
<span style="color:red;">- third match</span><br>

$(document).ready(function() {
  const regex = /^\s*-\s*/;
  $("#txt").keyup(function() {
    const entered = $('#textarea').val()
    const lines = entered.split(/\n/);

    let spans = "";
    for (const line of lines) {
      if (regex.test(line)) {
        spans += "<span style='color:red;'>- " + line.replace(regex, '') + "</span><br/>";
      }
    }

    $(".results").html(spans);
  });
});
.row {
  background: #f8f9fa;
  margin-top: 20px;
  padding: 10px;
}

.col {
  border: solid 1px #6c757d;
}
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>

<div class="container">
  <div class="row">
    <div class="col-12">
      <form>
        <textarea id="textarea" rows="5" cols="60" placeholder="Type something here..."></textarea>
      </form>
    </div>
    <div class="col-12 results"></div>
  </div>
</div>

因此,基本上脚本应该将 textarea 值从以“-”开头的行拆分到以“-”开头的下一行。

代码片段也可在此处获得:https ://jsfiddle.net/zecaffe/f7zv3udh/1/

标签: javascripthtmljquery

解决方案


为什么不只是一个分裂\n-

$(document).ready(function() {

  $("#textarea").keyup(function() {

    const entered = $('#textarea').val()
    const lines = entered.split(/\n-/);
    
    let spans = "";
    lines.forEach((l,i)=>{
      // remove the first -
      if(i===0 && l[0]==="-") l = l.slice(1)
      spans += "<span style='color:red;'>- " + l + "</span><br/>";
    })

    $(".results").html(spans);
  });
});
.row {
  background: #f8f9fa;
  margin-top: 20px;
  padding: 10px;
}

.col {
  border: solid 1px #6c757d;
}
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>

<div class="container">
  <div class="row">
    <div class="col-12">
      <form>
        <textarea id="textarea" rows="5" cols="60" placeholder="Type something here..."></textarea>
      </form>
    </div>
    <div class="col-12 results"></div>
  </div>
</div>


推荐阅读