Kev'n Roberts

June 2009 - Posts

Regular Expressions Are Your Friend

 I recently came across this JavaScript code:

function phonescrub(elmt){
    str=elmt.value;str2="";ii=0;
    while (ii < str.length){
        ch=str.charAt(ii);
        kk=0;
        while (kk < 10){
            if (ch==""+kk){str2=str2+ch};
            kk++;
        }
        ii++;
    }
    elmt.value=str2;
}

It's a little difficult to decipher, so I'll interpret it.

  1. Start with the current value of the input element (str).
  2. Initialize the return value (str2) and an indexer (ii).
  3. Loop through each character in string "str."
  4. Loop through the numers 0 to 9.
  5. If the current character (ch) is equal to the number (kk) then append that character to the output string (str2).
  6. Increment kk [End number loop]
  7. Increment ii [End character loop]
  8. Assign the new value (str2) to the input element's value property.

Essentially, what this function does is it strips out all non-numeric characters.

This function has several issues (not the least of which is the variable names "str" and "str2"). But the main issue is the complexity. The method is 11 lines long and it took me 8 steps to explain what it is doing.

Using Regular Expressions, we can reduce 11 lines to 1:

function phonescrub(elmt){
    elmt.value = elmt.value.replace(/[^0-9]/g, '');
}

Here is what this new function does:

  1. Replace all non-numeric characters in the input element's value with an empty string.
  2. Assign that new string to the value of the input element.
It really doesn't get much simpler than that. And there are no quirky variables (like str and str2).
More Posts