I have been looking around for a function that counts the number of words in a textarea when I click the form submit button.
当我点击表单提交按钮时,我一直在寻找一个计算textarea中单词数量的函数。
I am trying to display a message to the user that if they click submit and have only entered 50 or less words. This will be a confirm message basically saying "You have entered less than 50 words, are you sure you would like to continue?"...or something.
我试图向用户显示一条消息,如果他们点击提交并且只输入了50个或更少的单词。这将是一条确认消息,主要是说“你输入的字数少于50个,你确定要继续吗?”......或者别的什么。
Cheers
4 个解决方案
#1
2
HTML:
<form id="confirmForm">
<textarea id="moreThan50"></textarea>
<button type="submit">Submit</button>
</form>
JS:
$('#confirmForm').submit(function(ev){
var wordCount = $('#moreThan50').val().split(/\s/g).length;
if (wordCount < 50) {
if (!confirm('Less than 50 words, are you sure you want to submit?')) {
ev.preventDefault();
}
}
});
See demo
#2
3
You should use split
method using a space as a splitter, and then you take the length of the array.
您应该使用空格作为拆分器的拆分方法,然后获取数组的长度。
var wordCount = $('textarea').val().split(' ').length
#3
2
Another method, you can use regex and count 'words' using \b
:
另一种方法,你可以使用正则表达式并使用\ b计算'单词':
var words = $('#textareaid').val().match(/\b(\w+)\b)/g).length;
Ninja-Edit Oops, should have been .val
not .text
Ninja-Edit Oops应该是.val not .text
#4
1
You can split at word boundaries using regular expressions..
您可以使用正则表达式在单词边界处拆分。
$('form').submit(function(){
var words = $('textarea', this).val().split(/\b\W/);
if (words.length < 50){
// propmpt here.. and allow or cancel the submit..
}
});
#1
2
HTML:
<form id="confirmForm">
<textarea id="moreThan50"></textarea>
<button type="submit">Submit</button>
</form>
JS:
$('#confirmForm').submit(function(ev){
var wordCount = $('#moreThan50').val().split(/\s/g).length;
if (wordCount < 50) {
if (!confirm('Less than 50 words, are you sure you want to submit?')) {
ev.preventDefault();
}
}
});
See demo
#2
3
You should use split
method using a space as a splitter, and then you take the length of the array.
您应该使用空格作为拆分器的拆分方法,然后获取数组的长度。
var wordCount = $('textarea').val().split(' ').length
#3
2
Another method, you can use regex and count 'words' using \b
:
另一种方法,你可以使用正则表达式并使用\ b计算'单词':
var words = $('#textareaid').val().match(/\b(\w+)\b)/g).length;
Ninja-Edit Oops, should have been .val
not .text
Ninja-Edit Oops应该是.val not .text
#4
1
You can split at word boundaries using regular expressions..
您可以使用正则表达式在单词边界处拆分。
$('form').submit(function(){
var words = $('textarea', this).val().split(/\b\W/);
if (words.length < 50){
// propmpt here.. and allow or cancel the submit..
}
});