如何检查URL字符串是否不包含以下字符串:test/test/posts/search/1234567
,这样当我提供以下网址时:test/test/1234567
match
函数将返回:{{1} }?
更新
如果我在网址中提供["test/test/1234567", "test/test/", "", "1234567"]
,我想在/posts/search
函数中省略此正则表达式。
re.test(url)

答案 0 :(得分:1)
你几乎就在那里,你只需要将第二个捕获组选为?
量词,意味着 0或1次出现,贪心:
var url = "test/test/posts/search/1234567"; // result: null
var urlPrefix = 'test/test/';
if (!url.includes("posts/search/")) {
var re = new RegExp('(' + urlPrefix + ')(posts/search/)?([0-9]+)', 'i');
// ^
console.log(url.match(re));
}
else {
console.log(url + " contains 'posts/search/'!");
}