Javascript error: “val.match is not a function”

2019-04-03 07:35发布

I used the match function for regular expression.

the code I use is

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

but the javascript errors with

"val.match is not function"

I cant find what the problem is,

thanks in advance

3条回答
Ridiculous、
2楼-- · 2019-04-03 08:11

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);
}

2) 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);
}

查看更多
时光不老,我们不散
3楼-- · 2019-04-03 08:16

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*$)"

查看更多
何必那么认真
4楼-- · 2019-04-03 08:30

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);
}
查看更多
登录 后发表回答