简体   繁体   English

jQuery / JS-检测/匹配URL字符串以确定其类型

[英]jQuery / JS - Detecting / Matching an URL string to determine it's type

I have two URLs types, (TYPE A) 我有两种网址类型,(TYPE A)

/items

Or /items/XXXX with a trailing number (TYPE B) 或/ items / XXXX后缀为数字(TYPE B)

/items/187
/items/12831

I would like to know how to detect if the URL is type A or Type B 我想知道如何检测URL是A型还是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 . 这将首先检查数字版本,如果失败,则至少检查/items ...如果确定是一个或另一个,则可以省略第二个if并仅使用else

You can split the pathname on / , and do a parseInt() on the last item in the Array. 您可以在/上分割pathname ,并在Array的最后一项上执行parseInt()

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. 如果成功将其解析为数字,则为B类型,否则为A类型。

Note that this will fail if you have the number 0 for the number. 请注意,如果数字为0 ,则此操作将失败。 If 0 is a possibility, then you could just add 1 to the number. 如果可能为0 ,则只需将数字加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)
}
// /items/1233
if (url.match('\\/items/\\d+'))
{

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

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM