gpt4 book ai didi

javascript - Match a URL with placeholders 与 URL with filled placeholders

转载 作者:行者123 更新时间:2023-11-30 20:31:29 26 4
gpt4 key购买 nike

我正在尝试匹配两个 URL,一个带有占位符,一个带有 Angular 中的填充占位符和 TypeScript。

例如

URL 占位符被填充之前:

http://this/is/{placeholder1}/{placeholder2}/my/url?limit=10&offset=5

URL after 占位符被填充:

http://this/is/100Banana/200Apple/my/url?limit=10&offset=5

目标是将这两个 URL 与 Regex 匹配并获得匹配项。其中一个问题是,占位符可以填充 URL 允许的任何内容。

第一次尝试是在 Regex 匹配之前用 [^/]+ 之类的 Regex 替换占位符。但这仅在占位符位于 URL 末尾时才有效。

最佳答案

如果您只需要匹配它们,那么您不需要正则表达式。你可以这样做。

const str1 = 'http://this/is/{placeholder1}/{placeholder2}/my/url?limit=10&offset=5';
const str2 = 'http://this/is/100Banana/200Apple/my/url?limit=10&offset=5';

// url1: url with placeholders
// url2: url with filled placeholders
const compareUrls = (url1, url2) => {
const u1 = url1.split('/');
const u2 = url2.split('/');

if (u1.length !== u2.length) { return false; }

for (let i = 0; i < u1.length; i++) {
if (u1[i].startsWith('{placeholder')) { continue; }
if (u1[i] !== u2[i]) { return false; }
}
return true;
};

console.log(compareUrls(str1, str2));

关于javascript - Match a URL with placeholders 与 URL with filled placeholders,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50293004/

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