Reputation: 37
I'm wanting to create a similar thing to the character counter on this website - https://character-counter.uk/. However, instead of counting every character I only want to count hashtags. So if I entered #happy and #sad the counter would return the number 2.
I'm new to javaScript and jQuery so am not sure how I could get this to happen.
Say I have this html
<textarea rows="16" class="form-control"></textarea>
<div class="remaining-counter">Characters Counted: <span
class="well text-well">0</span></div>
I want the 0 belonging to the text-well span to jump up once whenever a hashtag is typed into the text area.
I've been tinkering around with some things but so far can only come up with this code
var count = 0;
$("textarea").on("input", function() {
if ($(this).val().match(/#/)) {
$('.text-well').html(count++);
} else {
return;
}
});
When entering it into the character counter site using the console the counter still counts up whenever I start typing into the textarea and then resets and starts counting up in twos when a # is entered.
Any help is appreciated.
Upvotes: 1
Views: 920
Reputation: 9096
This will count hash tags, requiring each pound sign counted to be followed by at least one word character:
$("textarea").on("keyup", function() {
var matches = $(this).val().match(/#\w+\b/g);
var count = matches ? matches.length : 0;
$('.text-well').html(count);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea rows="10" class="form-control"></textarea>
<div class="remaining-counter">Characters Counted: <span
class="well text-well">0</span></div>
Basically:
.match(pattern).length
to get the number of matches, remembering to use the g
flag so you actually count all matches./#/
works fine. If you want to match hash tags, ensure the hashtag is followed by a letter by using /#\w/
.keyup
event to ensure your count is updated on every letter press.Upvotes: 0
Reputation: 3040
var count = 0;
$("textarea").on('change keyup paste', function() {
if ($(this).val().match(/#/)) {
$('.text-well').html(count++);
}
});
Upvotes: 0
Reputation: 337560
To achieve this you can simply use the match()
method to find the number of hashtags within the value of the given textarea
, something like this:
$("textarea").on("input", function() {
var text = $(this).val();
var count = (text.match(/(^|\W)(#[a-z\d][\w-]*)/g) || []).length;
$('.text-well').html(count);
}).trigger('input');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<textarea rows="10" cols="40" class="form-control">Lorem #ipsum dolor #sit amet #consectetur adipiscing</textarea>
<div class="remaining-counter">Hashtags Counted: <span class="well text-well">0</span></div>
Note that I got the hashtag regex from this question
Upvotes: 2