Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/458.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 尝试与正则表达式匹配时,有一个in if语句_Javascript - Fatal编程技术网

Javascript 尝试与正则表达式匹配时,有一个in if语句

Javascript 尝试与正则表达式匹配时,有一个in if语句,javascript,Javascript,脚本已停止运行,当正则表达式不匹配时,当我尝试在if语句中使用它时,脚本错误无法读取null的属性“1”。如果我想在if语句中使用它,如何修复它 var titleDescription = "doesNotMatchThis"; var tempMatch = titleDescription.match(/(matchThis)/i); if (tempMatch[1]) { //do this } else { //do that } 您可以首先检查tempMatch的非匹配字符串 if

脚本已停止运行,当正则表达式不匹配时,当我尝试在if语句中使用它时,脚本错误无法读取null的属性“1”。如果我想在if语句中使用它,如何修复它

var titleDescription = "doesNotMatchThis";
var tempMatch = titleDescription.match(/(matchThis)/i);
if (tempMatch[1]) { //do this }
else { //do that }
您可以首先检查tempMatch的非匹配字符串

if (tempMatch && tempMatch[1]) {
    // ...
}
使用测试方法。它根据匹配与否返回true或false

var regex1 = RegExp('foo*');
var regex2 = RegExp('foo*','g');
var str1 = 'table football';

console.log(regex1.test(str1));
// expected output: true
请参阅以下网址:

如果字符串与表达式匹配,它将返回一个数组 包含整个匹配字符串作为第一个元素,后跟 括号中捕获的任何结果。如果没有匹配项,则为null 返回

您可以简单地测试is tempMatch是否为。如果是,则所有子匹配也将是:

变量titleDescription='doesNotMatchThat'; var tempMatch=titleDescription.match/matchThis/i; 如果匹配{ 控制台。日志“匹配”; }否则{ 控制台。日志“不匹配”;
}@IslamElshobokshy,不是吗?@IslamElshobokshy MDN认为是这样的-我会亲自写它,或者尝试重新编排句子,使用上面评论中链接的单词truthy。但是,这些只是细节:-什么。。。?我曾经使用过PHP,我认为如果没有[]也不能在if语句中使用它。@frosty在PHP中,您可能会使用preg_match,它返回许多匹配项。或者你的意思是在PHP中?我不确定是否会跟随。