gpt4 book ai didi

javascript - 检查 .match() 结果是否为空

转载 作者:行者123 更新时间:2023-12-04 08:33:35 26 4
gpt4 key购买 nike

我运行这个正则表达式 .match() :

var pattern = /property="og:description"\scontent="(.+?)"/;   
var matches = data.match(pattern);

if (matches[1]) {
var = description = matches[1];
}
但偶尔,我会收到此错误:
Uncaught TypeError: matches is null
我该怎么做才能检查 matches[1]是不是空的?
到目前为止我尝试过的
我试过这个:
if (matches && matches[1]) {
if (matches.length && matches[1].length) {
if (matches[1] != null) {
if (matches[1] != undefined && matches[1] != null) {
偶尔还是会出现这个错误。显然我错过了一些东西。

最佳答案

删除 [1]来自 matches当你检查它有一个值。错误是因为您试图通过索引访问空值。

let pattern = /property="og:description"\scontent="(.+?)"/;   

['foobar', 'property="og:description" content="abc"'].forEach(data => {
let matches = data.match(pattern);
let description = 'no match';
if (matches)
description = matches[1];

console.log(description);
});

关于javascript - 检查 .match() 结果是否为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64911337/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com