JavaScript match is not a function

| 9 Comments

Recently, I was helping another developer debug an issue with the JavaScript match function. We were experiencing a consistent error of ‘JavaScript match is not a function’.

A simplified version of the code we were dealing with would look something like this:

var str = document.getElementById('Name');
if(str.match('/\?/')){
   alert('Invalid String');
}

Our code was a bit more complicated, but this captures the general idea. The issue is pretty obvious once you realize what is, but when you’re deep in code it doesn’t immediately jump out at you. We were calling match on something that wasn’t a string. We should’ve been calling it on the value of that element, not the element itself.

The ‘match is not a function’ error will be thrown whenever the match function is called on something that isn’t a string. This includes variables that are undefined. If you can’t always ensure that your elements will be string you can validate them using the following code:

typeof YOURVARIABLE == 'string'

You can also use this block of code to see if what you think is a string actually is something else.