开发者

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

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:

"val.match is not function"

What is the problem?


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


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜