Javascript 限制字符串中每个单词的长度
有没有办法限制字符串中每个单词的长度 例如:Javascript 限制字符串中每个单词的长度,javascript,jquery,Javascript,Jquery,有没有办法限制字符串中每个单词的长度 例如: 循环遍历字符串中的每个单词 如果单词长度超过X个字符,则显示弹出消息,并且不提交表单 编辑:我的最终代码: $("#comment-form").submit(function(event) { var str = $("#comment-box").val(), limit = 135; var wordList = str.split(' '); $(wordList).each(function(i, word) {
$("#comment-form").submit(function(event) {
var str = $("#comment-box").val(), limit = 135;
var wordList = str.split(' ');
$(wordList).each(function(i, word) {
if(word.length > limit) {
alert("Your comment has a string with more than " + limit + " characters. Please shorten it.");
event.preventDefault();
}
});
});
试试这个:
var str = "This is the test string that contains some long words";
var wordList = str.split(' ');
var limit = 4;
$(wordList).each(function(i, word){
if(word.length >= limit){
alert(word);
}
});
您可以使用以下函数
<script>
var string = "Please be sure question to answer the question";
function checkWordLength(string)
{
var string_array = string.split(" ");
for(var i=0; i<string_array.length; i++)
{
var word = string_array[i];
var word_length = word.length;
if(word_length>6) return false;
}
}
checkWordLength(string);
</script>
var string=“请确保问题能够回答问题”;
函数checkWordLength(字符串)
{
var string_array=string.split(“”);
对于(var i=0;i6)返回false;
}
}
校验字长(字符串);
此示例在返回false时使用正则表达式,请确保从
onSubmit
方法返回false,您可以发布过来代码吗?我在问如何做一些我不知道该怎么做的事情。没有代码。答案是:是的,有。函数名不起作用,因为您向其中传递的是字符串而不是单词。
function CheckString(string, character_limit)
{
var word = /\w+/igm;
var match;
while((match = word.exec(string)) !== null) {
if(match[0].length > character_limit)
{
alert(match[0]);
return false;
}
}
return true;
}
var character_limit = 5;
var string = 'this is a string of words and stuff even';
CheckString(string, character_limit);