javascript - 正确拆分文本区域值 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/
解决方案
为什么不只是一个分裂\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>
推荐阅读
- python - 创建 Tkinter 文本并使以前的文本上升
- latex - 寻找大型乳胶文件(~200 页/1mb+)来测试压缩实现
- mysql - MySql 5.7,最大 varchar 列长度为 768?
- python - 无法使用 Python OpenANT 库初始化 ANT+ 节点
- php - Codeigniter - 未收到电子邮件
- swift - 希腊字符函数(为了好玩)
- python - python 绘图和图像查看库,具有等效的 MATLAB 数据提示
- multithreading - 同时使用 pyaudio 和语音识别
- simulation - 如何使用 Anylogic 在仓库操作中为拣货流程创建订单
- python-3.x - 为什么用户操作无法访问 tkinter Entry 小部件