jQuery / JS - Detecting / Matching an URL string to determine it's type
I have two URLs types, (TYPE A)
/items开发者_JAVA技巧
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
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
.
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.
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)
}
// /items/1233
if (url.match('\\/items/\\d+'))
{
}
// /items/
else if (url.match('\\/items/'))
{
}
精彩评论