views:

67

answers:

6

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.

+1  A: 

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

jayrdub
+2  A: 

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;
});
Anurag
Yeah, this works. Or constructing a new array from scratch as seen in a couple answers below works just as well. Thanks to everyone for the quick responses... zounds.
Jope
be careful with it's compatibility ;) [filter](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/filter)
Reigel
+1  A: 

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>");
}
treeface
A: 

Answering my own question in case anyone runs into this same problem in the future...

It looks like building an additive array of qualified elements rather than splicing the chaff from the original works better in this case, since the array length is changing on each cycle and lingering whitespace also can screw with your character count. (i.e. "This string of text " is spliced to ["This","string","of","text",""] where this last empty entry will count toward the next entry's character count.)

So this is now doing the trick for me:

var query = $('input').val().split(" ");
var qList = [];
var i=0;
for (i=0; i<query.length; i++){
  if (query[i].length >= 3){
    qList.push(query[i]);
  }
}

Hope this is of use.

Jope
You should probably accept the answer from Anurag since he beat you to your own punch
jayrdub
A: 

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]);
  }
} 
jebberwocky
+1  A: 

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+/);
Andrew Dunn