代码之家  ›  专栏  ›  技术社区  ›  shin

如何使用javascript选择art-8而不是cart-8

  •  0
  • shin  · 技术社区  · 15 年前

    示例url如下所示,

    http://www.mywebsite.com/art-8.asp?id=435&iPageID=43

    不过,这将拿起一个与购物车-8的网址,我不想那样。

    我只想在url中选择art-8而不是cart-8。

    if (location.pathname.indexOf('art-8') > 0){
    
    ...............
    

    我需要正则表达式吗?

    提前谢谢。

    4 回复  |  直到 15 年前
        1
  •  1
  •   PleaseStand    15 年前
    if (/\/art-8\/?$/.test(location.pathname)) {
        ...
    }
    

    将匹配以结尾的任何路径名 /art-8 /art-8/

    var parts = location.pathname.split('/').slice(1);
    if(parts[parts.length - 1] == '') parts = parts.slice(0, -1);
    if(parts[parts.length - 1] == 'art-8') {
        ...
    }
    

    编辑: art-8 不必在末尾,但前面有斜线:

    if (/\/art-8/.test(location.pathname)) {
        ...
    }
    

    第8条 c 在它之前(路径名将始终以斜线开头,因此之前将始终至少有一个字符,这将起作用):

    if (/[^c]art-8/.test(location.pathname)) {
        ...
    }
    

    ? 接下来是什么,所以即使我给出的前两个示例也适用于您给出的特定示例URL .asp 8 .

        2
  •  0
  •   thejh    15 年前

    这个regexp呢?

    [^c]art-8
    
        3
  •  0
  •   Lee    15 年前

    if (location.pathname.indexOf('/art-8/') > 0) {
    

    除了 “art-8”在结尾,没有斜线。您可以为特殊情况添加另一个检查,不带尾随斜杠,并包括一个检查,以确保索引将其放在行的末尾。

    var rx=new RegExp("/art-8(/|$)");
    if( rx.test(location.pathname) ) {
      ...
    }
    

    w3schools有一个 fairly comprehensive reference

        4
  •  0
  •   Tim Pietzcker    15 年前

    regex的方法是使用单词边界锚:

    /\bart-8\b/ 只会匹配 art-8 ,不是 cart-8 art-80 .

    \b 单词字符和非单词字符(或字符串的开始/结束)之间的匹配,其中单词字符定义为(在JavaScript中) [A-Za-z0-9_] .

    这种方法的优点是,如果您要查找的字符串周围没有字符,它也可以工作。