如何使用JavaScript正则表达式从URL中提取斜杠之间的值?
js正则提取url中斜杠之间的值
如何使用javascript正则表达式从url中提取斜杠(/)之间的值?以下是解决此问题的详细指南:
代码
let pattern = "{note}/:pakid:/corrinsdetail/{corrinsaleid}/{corrinspakid}/{corrinsinsta}/{corrinsvernr}/{verfrom}/{verto}/{name}/:tab:"; let url = "0001668882/41/corrinsdetail/0001023444/41/0020751259/0005/756/756/sap_basis/validitydetails"; function extractinfo(pattern, url) { const urlregex = new regexp(pattern.replace(/({|:)[w-]+(}|:)/g, "[\w-]+").replace(///g, "/")); if (!urlregex.test(url)) { throw new error("输入的url不符合pattern"); } let keys = pattern.split("/"); let values = url.replace(/(?|#).*/, "").split("/"); let result = {}; keys.foreach((v, i) => { if (/({|:)w+(}|:)/.test(v)) { result[v.replace(/({|:|})/g, "")] = values[i]; } }); return result; } console.log(extractinfo(pattern, url));
输出
该代码将输出以下对象:
{ note: "0001668882", pakid: "41", corrInsAleid: "0001023444", corrInsPakId: "41", corrInsInsta: "0020751259", corrInsVernr: "0005", verFrom: "756", verTo: "756", name: "SAP_BASIS", tab: "ValidityDetails" }
以上就是如何使用JavaScript正则表达式从URL中提取斜杠之间的值?的详细内容,更多请关注硕下网其它相关文章!