Reputation: 3
I am having problems to properly split textarea value. My current snippet split each line that starts with "-" and displays it as value of span element, but, it wont collect next line value which does not start with "-".
For example if I paste this text into textarea:
- first match
rest of first match
- second match
- third match
Script should output:
<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>
So, basically script should split textarea value from line that starts with "-" until next line which starts "-".
Code snippet is also available here: https://jsfiddle.net/zecaffe/f7zv3udh/1/
Upvotes: 0
Views: 73
Reputation: 33933
Why not just a split to the \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>
Upvotes: 1