JavaScript error: "val.match is not a function"

JavascriptMatch

Javascript Problem Overview


I’m using the match function with a Regular Expression.

The code I’m using is:

if(val.match(/^s+$/) || val == "" )

However, it produces the following error:

>none > "val.match is not function" >

What is the problem?

Javascript Solutions


Solution 1 - Javascript

I would say that val is not a string.

I get the

> val.match is not function

error for the following

var val=12; 
if(val.match(/^s+$/) || val == ""){
   document.write("success: " + val);
}

The error goes away if you explicitly convert to a string String(val)

var val=12; 
if(String(val).match(/^s+$/) || val == ""){
   document.write("success: " + val);
}

And if you do use a string you don't need to do the conversion

var val="sss"; 
if(val.match(/^s+$/) || val == ""){
   document.write("success: " + val);
}

Solution 2 - Javascript

the problem is: val is not string

i can think of two options

  1. convert to string: might be a good option if you are sure val has to be string

"Same as above answer"

var val=12; 
if(String(val).match(/^s+$/) || val == ""){
   document.write("success: " + val);
}

  1. skip the line: in my case, it was better to just check the val type and skip if it is not string, because it was not a good idea to run "match" function anyways.

val = 12;
if( val.match) {
  if(val.match(/^s+$/) || val == "" ) {
    document.write("success: " + val);
  }
} else {
    document.write("not a string: " + val);
}

Solution 3 - Javascript

NOTE: making this an answer as suggested above from my comment.

Definitely make sure val is defined and a String. Also, I'm guessing it's a typo that you don't have a slash before the 's' in your regex. If that is the case you can replace your if test with "if(val.match(/^\s*$)"

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionzahirView Question on Stackoverflow
Solution 1 - Javascriptchrisp7575View Answer on Stackoverflow
Solution 2 - JavascriptskipperView Answer on Stackoverflow
Solution 3 - JavascriptEric WendelinView Answer on Stackoverflow