Thursday, November 19, 2009

Javascript Regular Expression to test the last character in string

Today my colleague Martin asked me to look over his shoulder at a small problem he was facing, he was building a Search function in his application but got stuck with certain input.

If the search string ended on a character like ")" or a space (and maybe other non-alphanumeric characters), the search function returned nothing, even though it should have some matches.

We decided that the easiest way to solve this would be to delete all the faulty characters from the end of the string. This had to be done in (Server-side) JavaScript.

I came up with the following function: (and check below for the updated version)

<script type="text/javascript">
function testString(input){
    var regex = /[a-zA-Z0-9]$/;
    if(input.match(regex)){
        var match = input;
    } else {
        var nomatch = input.substring(0,input.length-1);
        var match = testString(nomatch);
    }
    return match;
}
</script>

What it does is the following:

  • We first define our regular expression
  • If this matches our input string, we will just return it
  • If it does not match our input string, we strip the last character off the string, and test it again.

This recursive test will continue as long as the regex is not macthed.

To test this functionality you can run the function like this:

document.write(testString("This is a string that end with some special chars & $ !!! ) "));
Which will output: "This is a string that end with some special chars".

Maybe someone enjoys this code, so I thought I'll share it :)

Update as my other colleague Marcus points out, there is a way more elegant way to implement this, making it so that is does not need to recurse. The updated code is below. Thanks Marcus :)

<script type="text/javascript">
function testString(input){
    while (!input.match(/[a-zA-Z0-9]$/))  {
        input = input.substring(0, input.length-1);
    }
    return input;
}
</script>


4 comments:

Marcus said...

He colleage, what about this:
Seems that the function could call itself again (maybe a StackOverflow security).

I think this one is better after all :P

function clearRotzooi(str)
{
while (!str.match("[A-Za-z0-9]$"))
{
str = str.substring(0, str.length-1);
}
return str;
}

Unknown said...

Thanks Marcus, I updated the post :)

JavaScriptBank.com said...

thank you very much for sharing.

martin said...

Thank's Bram (and Marcus), it works fine now. Good example of teamwork.