如何利用JavaScript正则表达式从URL中提取斜杠之间的值?
js正则表达式提取url中斜杠之间的值
如何利用javascript正则表达式从url中提取斜杠(/)之间的值?
下面提供了一段代码,可以帮助你解决这一问题:
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; }
使用方法:
- pattern:要匹配的正则表达式。
- url:要提取信息的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"; 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中提取斜杠之间的值?的详细内容,更多请关注硕下网其它相关文章!