限制字符串中每个单词的长度

时间:2014-07-05 04:08:09

标签: javascript jquery

有没有办法限制字符串中每个单词的长度?

例如:

  1. 遍历字符串中的每个单词
  2. 如果某个字词长于X字符数量,则会显示一条弹出式消息,但不提交该表单。
  3. 编辑:我的最终代码:

    $("#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();
            }
        });
    });
    

3 个答案:

答案 0 :(得分:4)

试试这个:

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);
    }
});

答案 1 :(得分:2)

您可以使用以下功能

<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>

答案 2 :(得分:1)

jsFiddle

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);

此示例在返回false时使用正则表达式,请确保从onSubmit的{​​{1}}方法返回false。