如何用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"; // 清洗url url = url.replace(/(?|#).*/, ""); // 模式替换 const urlregex = new regexp(pattern.replace(/({|:)[w-]+(}|:)/g, "[\w-]+").replace(///g, "/")); // 检验url是否符合模式 if (!urlregex.test(url)) { throw new error("输入的url不符合pattern"); } // 分割关键字和值 let keys = pattern.split("/"); let values = url.split("/"); let result = {}; // 匹配关键字和值 keys.foreach((v, i) => { if (/({|:)w+(}|:)/.test(v)) { result[v.replace(/({|:|})/g, "")] = values[i]; } }); console.log(result);
输出:
{ note: "0001668882", pakid: "41", corrInsAleid: "0001023444", corrInsPakId: "41", corrInsInsta: "0020751259", corrInsVernr: "0005", verFrom: "756", verTo: "756", name: "SAP_BASIS", tab: "ValidityDetails" }
以上就是如何用JavaScript正则表达式从URL中提取斜杠之间的值?的详细内容,更多请关注硕下网其它相关文章!