Reputation: 37
With the help of some people on this website I managed to create a hashtag counter here - https://codepen.io/timothycdavis17/pen/ZJeVBj.
Here is the code.
HTML
<section class="section-textarea bg-primary">
<div class="container">
<div class="row">
<div class="col-lg-12">
<div class="well textarea-well clearfix">
<textarea rows="16" class="form-control"></textarea>
<div class="buttons">
<div class="btn-group" role="group" aria-label="Basic example">
<button type="button" class="btn btn-secondary btn-primary btn-lg
count-button">Count</button>
<button type="button" class="btn btn-secondary btn-danger btn-lg
reset-button">Reset</button>
</div>
</div>
<div class="remaining-counter">Hashtags Counted: <span
class="well text-well">0</span></div>
</div>
</div>
</div>
</div>
</section>
CSS
body {
background: #0275D8;
}
.textarea-well {
color: #000;
text-align: center;
margin: 10% auto;
}
textarea {
margin-bottom: 20px;
}
.text-well {
background: lightblue;
}
.count-button {
margin-bottom: 20px;
}
.remaining-counter {
font-size: 30px;
margin-bottom: 20px;
}
jQuery
$(".count-button").click(function() {
var text = $("textarea").val();
var count = (text.match(/(^|\W)(#[a-z\d A-Z\D][\w-]*)/g) || []).length;
$('.text-well').html(count);
var seen = {};
$('textarea').each(function() {
var txt = $(this).text();
if (seen[txt])
$(this).remove();
else
seen[txt] = true;
});
}).trigger('click');
$(".reset-button").click(function() {
$("textarea").val(' ');
$('.text-well').html(0);
}).trigger('click');
After it was made I was asked whether it would be possible to not count any duplicate hashtags that are entered into the textarea and maybe error underline theme with a red squiggly line.
I've had a look around this website for answers but couldn't seem to find one that worked.
Any help is appreciated.
Upvotes: 1
Views: 1668
Reputation: 4113
Just use a temp array to filter out the duplicates.
// save the matches instead of immediately counting
var tags = text.match(/(^|\W)(#[a-z\d A-Z\D][\w-]*)/g) || [];
// init empty array for holding unique matches
var uTags = [];
// loop through matches
$.each(tags, function(index, value){
// if match is not in holding array array, add it to holding array
if(uTags.indexOf(value) == -1) uTags.push(value);
});
// get count from holding array which will only have one copy of each match
var count = uTags.length;
Here is a fork of your codepen with the above code.
Upvotes: 1