0

I would like to execute a process on the page load depending on what the hash in the URL is. I think I will need RegEx because I am looking for a pure JavaScript solution (no library dependencies).

What I am trying to do is if the hash is "#/products", then I will call "myIndex()" else if the hash is "#/products/3", then I will call "myDetail(id)" where "id" is a variable to the product number.

Anybody have a good idea on how to achieve this?

1 Answer 1

5

Here’s a solution that checks for the literal string '#/products' first, avoiding the regular expression where it’s unnecessary.

var hash = location.hash,
    regexID = /^#\/products\/(\d+)$/,
    matches;

if (hash == '#/products') {
  myIndex();
} else if (matches = hash.match(regexID)) {
  myDetail(matches[1]);
}
Sign up to request clarification or add additional context in comments.

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.