代码之家  ›  专栏  ›  技术社区  ›  me-me

javascript匹配特定的名称加上/和后面的字符

  •  0
  • me-me  · 技术社区  · 6 年前

    例如。

    const str = 'cars/ford';
    const isCars = str.match('cars');
    

    我要做的是确保它匹配cars,并且在/之后有斜杠和字符,然后返回true或false。 车后的人物/。。。会变,所以我无法匹配它。只需要匹配任何字符和/

    4 回复  |  直到 6 年前
        1
  •  0
  •   Emeeus    6 年前

    你可以用 test() 那就回来了 .

    const str = "cars/ford";
    
    const str2 = "cars/";
    
    var isCars = (str)=>/^cars\/./i.test(str)
    
    console.log(isCars(str));
    console.log(isCars(str2));
        2
  •  1
  •   Mark    6 年前

    var str = "cars/ford";
    var patt = new RegExp("^cars/");       //or var patt = /^cars\//
    var res = patt.test(str);              //true
    console.log(res);

    https://www.w3schools.com/js/js_regexp.asp

    https://www.rexegg.com/regex-quickstart.html

        3
  •  0
  •   Shan Robertson    6 年前

    (cars\/[a-z]+)
    

    这将只匹配小写字母,因此您可以添加 i 标记使其不区分大小写。

    /(cars\/[a-z]+)/i
    
        4
  •  0
  •   epascarello    6 年前

    var str = "cars/ford"
    var result = str.match(/^cars\/(.*)$/)
    console.log(result)
    ^     - start
    cars  - match exact characters
    \/    - match /, the \ escapes it
    (.*)  - capture group, match anything
    $     - end of line
    

    想象一下: RegExper