Javascript 错误:“val.match 不是函数”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4882691/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 14:35:42  来源:igfitidea点击:

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

javascriptmatch

提问by zahir

I used the match function for regular expression.

我对正则表达式使用了匹配函数。

the code I use is

我使用的代码是

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

but the javascript errors with

但是 javascript 错误

"val.match is not function"

I cant find what the problem is,

我找不到问题是什么,

thanks in advance

提前致谢

回答by chrisp7575

I would say that val is not a string.

我会说 val 不是字符串。

I get the "val.match is not function" error for the following

我收到以下内容的“val.match 不是函数”错误

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)

如果您显式转换为字符串 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);
}

回答by skipper

the problem is: val is not string

问题是:val 不是字符串

i can think of two options 1) convert to string: might be a good option if you are sure val has to be string

我可以想到两个选项 1) 转换为字符串:如果您确定 val 必须是字符串,则可能是一个不错的选择

"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.

2)跳过该行:在我的情况下,最好只检查 val 类型,如果它不是字符串则跳过,因为无论如何运行“match”函数并不是一个好主意。

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

回答by Eric Wendelin

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

一定要确保定义了 val 并且是一个字符串。另外,我猜这是一个错字,您的正则表达式中的“s”之前没有斜线。如果是这种情况,您可以将 if 测试替换为“if(val.match(/^\s*$)”