j doe
j doe

Reputation: 31

Extracting a specific param value from location.hash

I have hash of the following locations:

#/something/default
#/something/url1/user2
#/something/url2/url3/user3

What is the regex to extract only the first param value that start after something, i.e. i need to extract: default, url1, url2?

Upvotes: 0

Views: 45

Answers (2)

Get Off My Lawn
Get Off My Lawn

Reputation: 36351

Use split and get the 2nd array value:

let str1 = '#/something/default'
let str2 = '#/something/url1/user2'
let str3 = '#/something/url2/url3/user3'
let str4 = '#/something'

console.log(str1.split('/')[2])
console.log(str2.split('/')[2])
console.log(str3.split('/')[2])

// You can use a fallback like this if there is no value:
console.log(str4.split('/')[2] || 'Nothing to see here')

However, if you have your heart set on regexp, you can use this:

const regexp = /^#\/.+?\/(.+?)(\/|$)/

let str1 = '#/something/default'
let str2 = '#/something/url1/user2'
let str3 = '#/something/url2/url3/user3'
let str4 = '#/something'

console.log(str1.match(regexp)[1])
console.log(str2.match(regexp)[1])
console.log(str3.match(regexp)[1])

// You can use a fallback like this if there is no value:
console.log((str4.match(regexp) || [])[1] || 'Nothing to see here')

Upvotes: 2

nissim abehcera
nissim abehcera

Reputation: 831

This regex maybe doing the trick

(?<=#\/something\/)([^/\n]+)`

Upvotes: 0

Related Questions