0

I have two URLs types, (TYPE A)

/items

Or /items/XXXX with a trailing number (TYPE B)

/items/187
/items/12831

I would like to know how to detect if the URL is type A or Type B

if (TYPE A) ... else if (TYPE B) ....

Any suggestions for making this happen? Do I need a regex?

thanks

4 Answers 4

2

You can use a regex for the check, for example:

if(/\/items\/\d+/.test(url)) {
  //type B
} else if (/\/items/.test(url)) {
  //type A
}

This checks for the number version first, if that fails it checks for at least /items...if you're assured it's one or the other you can leave off the second if and just use the else.

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

Comments

1

You can split the pathname on /, and do a parseInt() on the last item in the Array.

if( parseInt( location.pathname.split('/').pop() ) ) {
    // was a successful number, so type B
} else {
    // was NaN, so type A
}

If it was successfully parsed as a number, it was type B, otherwise, type A.

Note that this will fail if you have the number 0 for the number. If 0 is a possibility, then you could just add 1 to the number.

Comments

1
if (type == '/items'){
  // Type A
} else if (type.match('/\/items\/[0-9]+/')){
  //Type B
} else {
  //Not either of the two
}

You can just match the string for the first part, the 2nd part could require regex if you need a third condition, otherwise, it's

if (type == '/items'){
  //A
} else {
  //B, (or anything else)
}

Comments

0
// /items/1233
if (url.match('\\/items/\\d+'))
{

}
// /items/
else if (url.match('\\/items/'))
{

}

1 Comment

This \d+ requires a regular expression, which means you'll need to either do '\\/items\\/\\d+' or /\/items\/\d+/. (You're missing the closing ) for your if() statements too.)

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.