1

A user on my site will enter a url of the form

    url = "https://www.website.com/shop/SHOPNAME/location/LOCATION"

I would like to extract the SHOPNAME and LOCATION substrings. The structure of the input url will always be of this form (or at least if they are not I will return an error). I have found answers on how to parse out particular characters, a certain suffix or a certain prefix but not two different substrings.

I require these strings to make an HTTP get request to my server. The alternative to extracting the strings, if I could send the full url over the HTTP request I can change my server side application easily for what is required. To do this I would need to prepend ever / with a \ (I think) - so alternatively if anyone had a solution for that it would be amazing!

Any help on this would be greatly appreciated! Thanks

2 Answers 2

4

Here a solution using a regex.

let url = "https://www.website.com/shop/SHOPNAME/location/LOCATION"
let regex = /\/shop\/(.*)\/location\/(.*)/i;
let matches = regex.exec(url);
if (matches.length === 3) {
  let shopname = matches[1];
  let location = matches[2];
  console.log(shopname, location);
}

Sign up to request clarification or add additional context in comments.

Comments

1

Since the structure of the input url will always be of that form, You can simply do:

url = "https://www.website.com/shop/SHOPNAME/location/LOCATION"
var subString = url.split( '/' );
var shopName = subString[4];
var shopLocation = subString[6];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.