-1

I have a URL from which I need to read a value. I need to take out the step from the URL. I want to write regex to do that

Let say that if I get the window.location.href, I get the following result

https://mypage/route/step-1/more-route/
https://mypage/route/step-5/more-route/

I want to get the step using regex. What is the best way to achieve that?

Thanks

  • `s.split("/")[4]` or `.match(/^(?:.*?\/){4}(.+?)\//)` might work, but If you post the actual URL with more specifics about where `step-n` might be and all of your possible edge cases, the prior operation can likely be improved significantly to match your use. What are all the requirements at hand? Thanks. – ggorlen Jul 01 '19 at 16:30
  • If the URLs all look like that, just grab one or more digits between a dash and a slash. Pretty straightforward, as regular expressions go. – Chris G Jul 01 '19 at 16:31
  • When you say step are you looking for a result of `step-1` or `1`? – Get Off My Lawn Jul 01 '19 at 16:35
  • @GetOffMyLawn question heading clearly suggest that you need to get number after certain word – Code Maniac Jul 01 '19 at 16:38

3 Answers3

1

You can use replace to replace everything except for the step number:

.+\/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))
Get Off My Lawn
  • 27,770
  • 29
  • 134
  • 260
0

You can use this regex

\/step-(\d+)
  • \/ - Matches /
  • step- - Matches word step-
  • (\d+) - Matches one or more digits (captured group)

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)))
Code Maniac
  • 33,907
  • 4
  • 28
  • 50
0

Split it up and then use the index.

let address = window.location.href; let addressArray= address.split('/') console.log(addressArray[3])