Home>

I want to match only paths consisting of English strings or hyphens.

as a condition
  • Do not match if there is nothing
  • Do not match if the hierarchy continues further
  • Do not match if the extension has an extension, such as".css"or".json"
There are two points:

.

Examples

I want the following behavior.

"/ JasonStatham" // matches
"/ Jason-Statham" // matches
"/Jason-Statham.json" // doesn't match
"/Jason/reset.css" // doesn't match
"/ Jason/Statham" // doesn't match
"/" // don't match

I tried a lot, but it didn't work.

/\/(\ w |-) + [^ \ /.+] /. test ("/ Jason/reset.css")
// true
/\/[^(\w|-)\/.+]/.test("/Jason/reset.css ")
// error

I haven't thought of it for a while, so I have a question.

  • Answer # 1

    I think you should use an anchor.^represents the beginning of the line, and$represents the end of the line.
    /^ \/[a-zA-Z-] + $/satisfies the condition if only the above example is considered.

    var parameters = [
      "/ JasonStatham",
      "/ Jason-Statham",
      "/Jason-Statham.json",
      "/Jason/reset.css",
      "/ Jason/Statham",
      "/"
    ];
    var pattern =/^ \/[a-zA-Z-] + $/;
    parameters.map (str =>pattern.test (str))
      .forEach (result =>{console.log (result)});

  • Answer # 2

    If there is an omission, please indicate the condition

    var a = [
      "/ JasonStatham",
      "/ Jason-Statham",
      "/Jason-Statham.json",
      "/Jason/reset.css",
      "/ Jason/Statham",
      "/",
      ];
    var reg = new RegExp ("^/(?!. * \\. (css | json) $) [\\ w \\. \\-] +? $");
    a.forEach (function (x) {
      console.log (x + ":" + (x.match (reg)? "OK": "NG"));
    });