简体   繁体   中英

JavaScript filtering an array of <input> values by character count

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.

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, completely 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.net/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]);
  }
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM