我有一个URL,需要从中读取值。我需要从URL中删除该步骤。我想写正则表达式来做到这一点
假设我得到window.location.href
,就会得到以下结果
https://mypage/route/step-1/more-route/
https://mypage/route/step-5/more-route/
我想使用正则表达式一步。做到这一点的最佳方法是什么?
谢谢
答案 0 :(得分:1)
您可以使用replace替换step
号以外的所有内容:
.+\/step-(\d+)\/.+
const url1 = 'https://mypage/route/step-1/more-route/'
const url2 = 'https://mypage/route/step-5/more-route/'
const url3 = 'https://mypage/route/step-13/more-route/'
const step = (url) => url.replace(/.+\/step-(\d+)\/.+/, '$1')
console.log(step(url1))
console.log(step(url2))
console.log(step(url3))
答案 1 :(得分:0)
您可以使用此正则表达式
\/step-(\d+)
\/
-匹配/
step-
-匹配单词step-
(\d+)
-匹配一个或多个数字(捕获的组)
let urls = ['https://mypage/route/step-1/more-route/'
,'https://mypage/route/step-5/more-route/']
let getStep = (url) => {
let match = url.match(/\/step-(\d+)/i)
return match && match[1]
}
urls.forEach(url=> console.log(getStep(url)))
答案 2 :(得分:0)
将其拆分,然后使用索引。
let address = window.location.href;
let addressArray= address.split('/')
console.log(addressArray[3])