split textarea value properly jQuery regex - javascript

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/

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>

Related

How to make it so that previous answer is displayed when number is clicked after equals in js calculator?

I need to make it so that the previous result is displayed when the user presses a num after pressing equals... how do I do it? And just fyi I am just helping my friend make the code for his calculator clean - his was very messy - if you want I can show you his code as well.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<div class='container'>
<div class='answer'>
<p class='returnAnswer'>Answer Will Come Here</p>
</div>
<div class='buttonDiv'>
<div class='button'>0</div>
<div class='button'>1</div>
<div class='button'>2</div>
<div class='button'>3</div>
<div class='button'>4</div>
<div class='button'>5</div>
<div class='button'>6</div>
<div class='button'>7</div>
<div class='button'>8</div>
<div class='button'>9</div>
<div class='equals'>=</div>
<div class='button'>c</div>
<div class='button'>+</div>
<div class='button'>-</div>
<div class='button'>x</div>
<div class='button'>÷</div>
<div class='button'>.</div>
<div class='button'>%</div>
</div>
</div>
</body>
</html>
<script type="application/javascript" src="/share.js"></script>
<script>
var eq = "";
var ans = eval(eq);
$('.button').click(function() {
eq += $(this).text();
$('.returnAnswer').text(eq);
});
$('.equals').click(function() {
$('.returnAnswer').text(ans);
});
</script>
This was a fun thing to do.... Here is what I have done to your code
Added some styles to the button (not important, but makes it easier to click)
Added a class named num to each number button, that will be used to reset the display if any button is clicked following '=' button.
Removed 'equals' class from '=' button and added it as an ID
Added code to clear the display when 'C' is clicked
Changed buttons 'x' to ' * ' and '÷' to '/' as otherwise eval function will not work
Changed back to 'x' and '÷', and added 2 lines inside equals.clicked to replace these with correct operators
Check the Code snippet
var eq = "";
var ans = eval(eq);
var equalsCliked = false;
$('.button').not("#equals, #cbutton").click(function () {
if ($(this).hasClass('num') && equalsCliked)
eq = "";
eq += $(this).text();
$('.returnAnswer').text(eq);
equalsCliked = false;
});
$('#equals').click(function () {
equalsCliked = true;
eq = eq.split("÷").join("/");
eq = eq.split("x").join("*");
ans = eval(eq);
eq = ans;
$('.returnAnswer').text(ans);
});
$('#cbutton').click(function () {
equalsCliked = false;
eq = "";
ans = eval(eq);
//eq = ans;
$('.returnAnswer').text("");
});
.button {
border: 1px solid gray;
padding: 8px;
margin: 3px 3px;
float: left;
cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<div class='container'>
<div class='answer'>
<p class='returnAnswer' style="width:330px; padding: 10px; min-height:20px; border: 1px solid gray; border-radius: 2px;">Answer Will Come Here</p>
</div>
<div class='buttonDiv' style="background-color:yellow; float:left; width: 330px;">
<div class='button num'>0</div>
<div class='button num'>1</div>
<div class='button num'>2</div>
<div class='button num'>3</div>
<div class='button num'>4</div>
<div class='button num'>5</div>
<div class='button num'>6</div>
<div class='button num'>7</div>
<div class='button num'>8</div>
<div class='button num'>9</div>
<div id="equals" class='button'>=</div>
<div id="cbutton" class='button'>C</div>
<div class='button'>+</div>
<div class='button'>-</div>
<div class='button'>x</div>
<div class='button'>÷</div>
<div class='button'>.</div>
<div class='button'>%</div>
</div>
</div>
</body>

Set the selector cursor to a new position in contenteditable div [duplicate]

This question already has answers here:
How to set the caret (cursor) position in a contenteditable element (div)?
(13 answers)
Closed 2 years ago.
i've been making a text editor but i couldn't been able to get and set the "cursor" in a new position in the div with the content editable.
<form action="submitchapter.php" method="post">
<div class="input-group mb-3" style="margin-top:30px;">
<input type="text" class="form-control name" placeholder="Chapter Name" name="sname" value="No Title For The Chapter" required>
</div>
<div class="buttons shadow-sm">
<button style="padding:0; border:0px solid white; background-color:white;" type="button" id="buttonbold"><i class="fas fa-bold" id="bold"></i></button>
<input id="file-input" type="file" name="name" style="display: none;" />
</div><br>
<div class="containe shadow-sm" style="padding:20px; background-color:white;">
<div class="content" contenteditable="true" name="content" id="content" role="textbox" spellcheck="false"></div>
</div>
var content = document.getElementById("content");
var bold = document.getElementById("bold");
var content = document.getElementById("content");
$("#buttonbold").click(function(){
content.focus();
var valuelength = content.value.length - 4;
content.setSelectionRange(content.value.length,valuelength);
});
var boldactive = false;
$("#bold").click(function(){
if (boldactive == false) {
var content1 = content.innerHTML;
content.innerHTML = content1 + "<b>";
boldactive = true;
} else {
var content1 = content.innerHTML;
content.innerHTML = content1 + "</b>";
boldactive = false;
}
});
But nothing worked. I have tried with textarea too, but I think I'm doing something wrong.
<div> elements have no value property
$("#buttonbold").click(function(){
content.focus();
var valuelength = content.textContent.length - 4;
content.setSelectionRange(content.textContent.length,valuelength);
});
.
<div> elements do not have a setSelectionRange method either,
so here is a solution to make this kind of selection for elements using the contenteditable property:
const myDiv = document.getElementById('my-div')
, btSelectRange = document.getElementById('bt-select-range')
;
function setSelectionRangeCE(el, pos, len)
{
el.focus();
let range = document.createRange()
, sel = window.getSelection()
;
range.setStart(el.firstChild, pos)
range.setEnd(el.firstChild, pos+len)
sel.removeAllRanges()
sel.addRange(range)
}
btSelectRange.onclick=_=>
{
setSelectionRangeCE(myDiv,2,5)
}
#my-div {
margin: 1em;
padding: .7em;
width: 16em;
height: 3em;
border: 1px solid grey;
}
button {
margin: 1em;
}
<div id="my-div" contenteditable >hello world</div>
<button id="bt-select-range" > select range pos:2 len:5 </button>

Count each individual vowel in string upon click

Writing some js for an html file where i input a sentence (string). and when i click a button, it outputs the amount of each individual vowel, excluding y and not paying attention to punctuation. I cannot use var so i am trying to make this work using let. I believe i'm on the right path here,starting with the vowel a, yet if the sentence doesn't contain an a i get an error. I can't think of what to do next. Any thoughts?
'use strict';
let vButton = document.querySelectorAll('#vowels');
vButton.forEach(function(blip) {
blip.addEventListener('click', function(evt) {
evt.preventDefault();
console.log('click');
let vowelString = document.getElementById('roboInput'),
sentence = vowelString.value;
if (sentence !== '') {
let aMatches = sentence.match(/a/gi).length;
alert("a - " + aMatches);
}
vowelString.value = '';
});
});
a {
cursor: pointer;
}
.well-robot {
min-height: 340px;
}
.input-robot {
width: 100%;
min-height: 100px;
}
.output-robot {
border: 1px solid #000000;
min-height: 150px;
margin-top: 10px;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css">
<div class="container">
<div class="alert alert-info">
Hello! I'm a smart robot. I can do many interesting things. Type something below and click a button to watch me work!
</div>
<div class="row">
<div class="col-sm-4">
<img src="./robot.gif">
</div>
<div class="col-sm-8 well well-robot">
<textarea id="roboInput" placeholder="Input something here!" class="input-robot"></textarea>
<div class="btn-group btn-group-justified">
<a class="btn btn-default" id="vowels">Count Vowels</a>
<a class="btn btn-default" id="anagrams">Count Anagrams</a>
<a class="btn btn-default" id="distance">Word Distance</a>
</div>
<div id="robotResult" class="output-robot">
</div>
</div>
</div>
</div>
When there's no match for the regular expression, .match() returns null, not an empty array, so you can't get the length. You need to check for that.
let matches = sentence.match(/a/gi);
let matchLength = matches ? matches.length : 0;
alert('a - ' + matchLength);
If I understand your question correctly, you may want something like this:
'use strict';
let vButton = document.querySelectorAll('#vowels');
vButton.forEach(function(blip) {
blip.addEventListener('click', function(evt) {
evt.preventDefault();
//console.log('click');
let vowelString = document.getElementById('roboInput'),
sentence = vowelString.value;
if (sentence) {
let result = {a: 0, e: 0, i: 0, o: 0, u: 0 };
for(var i = 0, l = sentence.length; i < l; i++) {
if(result.hasOwnProperty(sentence[i]))
result[sentence[i]]++;
}
console.log(result);
}
vowelString.value = '';
});
});
a {
cursor: pointer;
}
.well-robot {
min-height: 340px;
}
.input-robot {
width: 100%;
min-height: 100px;
}
.output-robot {
border: 1px solid #000000;
min-height: 150px;
margin-top: 10px;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css">
<div class="container">
<div class="alert alert-info">
Hello! I'm a smart robot. I can do many interesting things. Type something below and click a button to watch me work!
</div>
<div class="row">
<div class="col-sm-4">
<img src="./robot.gif">
</div>
<div class="col-sm-8 well well-robot">
<textarea id="roboInput" placeholder="Input something here!" class="input-robot"></textarea>
<div class="btn-group btn-group-justified">
<a class="btn btn-default" id="vowels">Count Vowels</a>
<a class="btn btn-default" id="anagrams">Count Anagrams</a>
<a class="btn btn-default" id="distance">Word Distance</a>
</div>
<div id="robotResult" class="output-robot">
</div>
</div>
</div>
</div>

Replacing part of div in my preview with html entites

On my script I can preview my out put by clicking on my preview button.
In side my pre tags if there is a open <div> and close </div> found with < and > how can I just replace it with the html entities I have tried
$('.preview pre').html(str.replace(/</g, "<").replace(/>/g, ">"));
But because there are br tags in there it replaces the ones around br also which I do not want. I only just want to replace the ones around the open and close div's in side my pre tag.
Question: how can I just replace it with the html entities < and
> only round the open and close divs
Codepen Example Here
Script
<script type="text/javascript">
$('#preview-question').on('click', function (e) {
var editor = $('#question').val();
$('.preview').html(editor.replace(/\n/g, '<br/>'));
$('.preview pre').next('br').remove();
if ($('.preview').find("pre").length > 0){
var str = $('.preview pre').html();
$(".preview pre div").replaceWith("<div>");
//$('.preview pre').html(str.replace(/</g, "<").replace(/>/g, ">").next('div'));
$('.preview pre').html(str);
$('pre').each(function(i, block) {
hljs.highlightBlock(block);
});
}
});
</script>
I have make a for loop for detect only div element and remove all <br>. It's a bit ugly but work fine.
$('#preview-question').on('click', function (e) {
var editor = $('#question').val();
$('.preview').html(editor.replace(/\n/g, '<br/>'));
$('.preview pre').next('br').remove();
if ($('.preview').find("pre").length > 0){
var $str = $('.preview pre');
var pre = $str.html();
$str.html("");
pre = pre.replace(/<br>/g,"\n")
for(t=0;t<pre.length;t++){
if(pre.substr(t,1) == "<" && pre.substr(t+1,3) == "div"){
$str.html($str.html() + pre.substr(0,t).replace(/</g, '<'))
}else if(pre.substr(t,1) == "<" && pre.substr(t+1,4) == "/div"){
$str.html($str.html() + pre.substr(0,t+5).replace(/</g, '<'))
}
if(pre.substr(t,1) == ">" && pre.substr(t-3,3) == "div"){
$str.html($str.html() + pre.substr(t,1).replace(/>/g, '>'))
}
}
}
});
body {
background-color: #F0F0F0;
}
.panel {
box-shadow: 0 0 4px 0 rgba(0, 0, 0, 0.08), 0 2px 4px 0 rgba(0, 0, 0, 0.12);
}
.panel-default > .panel-heading {
background-color: #4d525b;
border-color: none;
color: #FFFFFF;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="panel panel-default">
<div class="panel-heading">
<h1 class="panel-title"></h1>
</div>
<div class="panel-body">
<div class="form-group">
<label class="col-lg-2">Title</label>
<div class="col-lg-10">
<input type="text" name="title" class="form-control" placeholder="Title" />
</div>
</div>
<div class="form-group">
<label class="col-lg-2">Question</label>
<div class="col-lg-10">
<textarea name="question" id="question" class="form-control" rows="10">
Hello this is some code
<pre>
<div class="">
</div>
</pre>
</textarea>
</div>
</div>
<div class="form-group">
<label class="col-lg-2"></label>
<div class="col-lg-10">
<div class="preview"></div>
</div>
</div>
</div>
<div class="panel-footer">
<div class="btn-group text-center">
<button type="submit" class="btn btn-primary">Submit</button>
<button type="button" id="preview-question" class="btn btn-default">Preview</button>
Cancel
</div>
</div>
</div>

How to clone, modify (increment some elements) before appending using jQuery?

I have an element that contains multiple elements inside it, what I need is to clone the element, but on every "new" element, I need to increment an element (the object number -see my script please-)
In the script I'm adding I need (every time I click on the button) to have : Hello#1 (by default it's the first one) but the first click make : Hello#2 (and keep on top Hello#1) second click = Hello#1 Hello#2 Hello#3 ... We need to keep the oldest hellos and show the first one.
var count = 1;
$(".button").click(function(){
count += 1;
num = parseInt($(".object span").text());
$(".object span").text(count);
var cont = $(".container"),
div = cont.find(".object").eq(0).clone();
cont.append(div);
});
.object{
width:100px;
height:20px;
background-color: gold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<button type="button" class="button">
create object
</button>
<div class="container">
<div class="object">
<p>
hello#<span>1</span>
</p>
</div>
</div>
You just have to change a little:
var count = 1;
$(".button").click(function() {
count += 1;
num = parseInt($(".object span").text());
var cont = $(".container"),
div = cont.find(".object").eq(0).clone();
div.find('span').text(count); // <------here you have to put the count
cont.append(div);
});
.object {
width: 100px;
height: 20px;
background-color: gold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<button type="button" class="button">
create object
</button>
<div class="container">
<div class="object">
<p>
hello#<span>1</span>
</p>
</div>
</div>
and if you want to simplify this more use this:
$(".button").click(function() {
var idx = ++$('.object').length; // check for length and increment it with ++
var cont = $(".container"),
div = cont.find(".object").eq(0).clone();
div.find('span').text(idx); // <------here you have to put the count
cont.append(div);
});
.object {
width: 100px;
height: 20px;
background-color: gold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<button type="button" class="button">
create object
</button>
<div class="container">
<div class="object">
<p>
hello#<span>1</span>
</p>
</div>
</div>
Use the following function, this is more modular and you can use it to update the count if you remove one of the elements
function updateCount() {
$(".object").each(function(i,v) {
$(this).find("span").text(i+1);
});
}
$(".button").click(function() {
num = parseInt($(".object span").text());
var cont = $(".container"),
div = cont.find(".object").eq(0).clone();
cont.append(div);
updateCount();
});
.object {
width: 100px;
height: 20px;
background-color: gold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<button type="button" class="button">
create object
</button>
<div class="container">
<div class="object">
<p>
hello#<span>1</span>
</p>
</div>
</div>

Categories

Resources