【发布时间】:2021-01-14 22:19:18
【问题描述】:
我有一个 array 或 strings。我需要在每个string 上获取URL 的值。我创建了一个function 和Regex 来完成此任务。它工作正常,但有一个我无法涵盖的边缘情况。当没有任何URL: 的值时,我得到错误:Cannot read property '1' of null。
这是我的代码:
const arrStr = [
`describe
url: https://url-goes-here-/1,
https://url-goes-here-/2,
https://url-goes-here-/3
});`
,
`
before(() => {
url: https://url-goes-here-/4
});
`,
`
before(() => {
url: https://url-goes-here-/5
});
`,
`describe
// nothing http link here
});
`
]
const getXrayUrl = str => str.match(/url:([^;]+)/)[1].trim().split('(')[0]; // cannot read property '1' of null
const allXrayUrls = arrStr.map(item => getXrayUrl(item));
如果我从array 中删除没有URL 值的string,我会得到以下输出:
[ 'https://url-goes-here-/1,\n https://url-goes-here-/2,\n https://url-goes-here-/3\n })',
'https://url-goes-here-/4\n })',
'https://url-goes-here-/5\n })' ]
我如何覆盖这个边缘情况并返回另一个 array 以及关卡中的所有 string?
【问题讨论】:
-
因为如果match不匹配,则返回null,而不是空数组。尝试获取 null 的 1 属性会引发错误(因为 null 不是对象)。因此,如果 match 返回 null,则替换为空数组,例如
(str.match(/url:([^;]+)/) || [])[1]所以如果没有匹配,表达式返回 undefined 而不是抛出错误。
标签: javascript arrays regex ecmascript-6