标签计数器
我想创建一个类似的东西在这个网站上的字符计数器 - https://character-counter.uk/。但是,我并不是要计算每个角色,而只是要计数标签。因此,如果我输入了#happy和#sad,计数器将返回数字2.标签计数器
我是新来的javaScript和jQuery,所以我不知道如何才能让它发生。
说我有这个网站
<textarea rows="16" class="form-control"></textarea>
<div class="remaining-counter">Characters Counted: <span
class="well text-well">0</span></div>
我想要的0属于文本的井孔跨度跳起来一次每当井号标签输入到文本区域。
我一直在与一些修修补补的事情四处但至今只能想出这个代码
var count = 0;
$("textarea").on("input", function() {
if ($(this).val().match(/#/)) {
$('.text-well').html(count++);
} else {
return;
}
});
当使用计数器仍然计数的控制台中输入入字符计数器网站每当我开始打字进入文本区域,然后重置并在#进入时开始以两个数字向上计数。
任何帮助表示赞赏。
要做到这一点,你可以简单地使用match()
方法查找给定textarea
的值内的井号标签的数量,这样的事情:
$("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>
注意,我得到了hashtag正则表达式从this question
test ## test count as 1 –
@GiorgioCatenacci所以它应该 - 它是一个hashtags的计数,而不是散列 –
这是正确的 - 这只是一个#标签,'#test' –
var count = 0;
$("textarea").on('change keyup paste', function() {
if ($(this).val().match(/#/)) {
$('.text-well').html(count++);
}
});
这会计算哈希标记,需要计算每英镑符号应遵循由至少一个单词字符:
$("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>
基本上是:
- 而不是努力保持计数器的轨道,做到整个每次计数。
- 使用
.match(pattern).length
获得匹配数,记住使用g
标志,以便实际计算所有匹配。 - 如果你只想计算哈希,
/#/
工作正常。如果您想匹配散列标签,请确保标签后面跟着一个字母/#\w/
。 - 使用
keyup
事件来确保每次按字母时更新您的计数。
的可能的复制[如何计算的串串发生?(https://stackoverflow.com/questions/4009756/how-to-count-string-occurrence-in-string) –
而不是每递增用户键入的时间,我建议在每个输入事件上进行全部计数。 –