如何使用JavaScript从URL中提取指定的路径字符串?
提取URL中的重置密码Token
以下几种实用方法可以帮你提取目标字符串:
方法1:分割路径字符串
通过location.pathname获取URL的路径部分,再拆分提取最后一段有效内容:
// 获取路径并分割为数组,过滤空项 const pathSegments = location.pathname.split('/').filter(segment => segment); // 取数组最后一项就是目标Token const resetToken = pathSegments[pathSegments.length - 1]; console.log(resetToken);
方法2:正则表达式匹配
针对resetPassword后的Token格式(字母+数字的长串),用正则精准匹配:
// 匹配resetPassword后的字母数字序列 const tokenPattern = /\/resetPassword\/([a-f0-9]+)/i; const match = location.href.match(tokenPattern); // 匹配成功则取捕获组内容,否则返回null const resetToken = match ? match[1] : null; console.log(resetToken);
方法3:使用URL API解析
现代浏览器支持原生URL对象,解析后处理路径更直观:
const url = new URL(location.href); const pathSegments = url.pathname.split('/').filter(segment => segment); const resetToken = pathSegments.pop(); console.log(resetToken);
注:如果之前用
location对象失败,大概率是没处理路径分割后的空字符串(比如路径开头的/会导致数组第一个元素为空),过滤空项后就能正确获取目标内容。
内容的提问来源于stack exchange,提问作者Isadora Garcia
相关产品推荐
相关产品推荐

