检查字符串是否不包含 URL 段并匹配它

Check if string does not contain URL segment and match it

如何检查URL字符串是否不包含以下字符串:test/test/posts/search/1234567,以便当我提供以下URL时:test/test/1234567 match 函数会 return: ["test/test/1234567", "test/test/", "", "1234567"]?

更新:

如果我在 URL 中提供 /posts/search 我想在 re.test(url) 函数中省略这个正则表达式。

// var url = "test/test/posts/search/1234567"; // desired result: null
var url = "test/test/1234567"; // result: ["test/test/1234567", "test/test/", undefined, "1234567"]
var urlPrefix = 'test/test/';
var re = new RegExp('(' + urlPrefix + ')(posts\/search\/)([0-9]+)', 'i');
console.log(url.match(re));

你快完成了,你只需要用 ? 量词使第二个捕获组可选,意思是 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/'!");
}