jquery - JavaScript filtering an array of <input> values by character count - Stack Overflow

This should be a quickie, but I'm scratching my head as to why this bit of JavaScript isn't w

This should be a quickie, but I'm scratching my head as to why this bit of JavaScript isn't working for me. The goal is to take the value of an input box (string of words separated by spaces), list these words as items in an array, and remove those which are fewer than 3 characters:

var typed = $('input').val();
var query = typed.split(" ");
var i=0;
for (i=0; i<query.length; i++) {
  if (query[i].length < 3) {
    query.splice(i,1);
  }
} 

Have this running onkeyup for the input box and it seems to work, but only about 50% of the time (strings of 1 and 2 characters somehow find their way into the array on occasion). Any suggestions would be hugely appreciated.

This should be a quickie, but I'm scratching my head as to why this bit of JavaScript isn't working for me. The goal is to take the value of an input box (string of words separated by spaces), list these words as items in an array, and remove those which are fewer than 3 characters:

var typed = $('input').val();
var query = typed.split(" ");
var i=0;
for (i=0; i<query.length; i++) {
  if (query[i].length < 3) {
    query.splice(i,1);
  }
} 

Have this running onkeyup for the input box and it seems to work, but only about 50% of the time (strings of 1 and 2 characters somehow find their way into the array on occasion). Any suggestions would be hugely appreciated.

Share Improve this question edited Sep 22, 2010 at 4:17 Reigel Gallarde 65.3k21 gold badges125 silver badges142 bronze badges asked Sep 22, 2010 at 4:10 JopeJope 471 silver badge5 bronze badges 0
Add a ment  | 

5 Answers 5

Reset to default 3

The problem is that you are iterating while removing the elements. Consider this array:

["he", "l", "lo world"]

Initially your loop starts at index 0 and removes "he" from the array. Now the new array is

["l", "lo world"]

In the next iteration i will be 1, and you will check "lo world"'s length, thus ignoring the "l" string altogether.

Use the filter method in Array to remove the unwanted elements.

var biggerWords = query.filter(function(word) {
    return word.length >= 3;
});

Besides the iterating problem, you may also see unexpected entries if you type multiple spaces

try

var query = typed.split(/\s+/);

This way it will split on any number of spaces, instead of each individual one

The problem is that you're slicing the array while counting forward. Think about it...if you take an index point out of the array, thereby shortening it by one, incrementing i and moving on to the next one actually moves one further than you want, pletely missing the next index. Increment i--, start at query.length-1, and make the condition that i>=0. For an example of this in action, check it out here:

http://jsfiddle/kcwjs/

CSS:

input {
    width:300px;
}​

HTML:

<input id="textbox" type="text" />
<div id="message"></div>​

Javascript:

$(document).ready(function() {
    $('#textbox').keyup(checkStrings);
});

function checkStrings(e) {
    var typed = $('#textbox').val();

    if (typed == "") return false;

    var query = typed.split(" ");
    var querylen = query.length;
    var acceptedWords = '';
    var badWords = '';

    for (var i = querylen-1; i >= 0; i--) {
        if (query[i].length < 3) {
            badWords += query[i] + " ";            
        } else {
            acceptedWords += query.splice(i,1) + " ";
        }
    }

    $('#message').html("<div>Bad words are: " + badWords + "</div>" +
                       "<div>Good words are: " + acceptedWords + "</div>");
}

Try this code, it get's rid of any 3 character words, as well as making sure no empty array elements are created.

typed.replace(/(\b)\w{1,3}\b/g,"$1");
var query = typed.split(/\s+/);

hey i think you should use a new array for the result. since you are removing the element in array. the length is changed. here is my solution

var typed = "dacda cdac cd k foorar";
var query = typed.split(" ");
var i=0;
var result = [];
for (i=0; i<query.length; i++) {    
  if (query[i].length >= 3) {
    result.push(query[i]);
  }
} 

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745295135a4621093.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信