Search code examples
javascriptregexuuid

Check for pattern match with UUIDv4 in JavaScript


I am looking for a pattern match with certain string before and after the uuid.

e.g.user/a24a6ea4-ce75-4665-a070-57453082c256/photo/a24a6ea4-ce75-4665-a070-57453082c256

const regexExp = new RegExp(/^user\/[0-9A-F]{8}-[0-9A-F]{4}-[4][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i);

console.log(regexExp.test("user/a24a6ea4-ce75-4665-a070-57453082c256")); // true

console.log(regexExp.test("user/a24a6ea4-ce75-4665-a070-57453082c256/photo")); // false

What I am expecting is to match user/{uuid}/* How to use a wildcard after the uuid?


Solution

  • If you want to match both, you can omit using the RegExp constructor as you are already using a literal and optionally match / followed by the rest of the string.

    The [4] can be just 4

    const regexExp = /^user\/[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}(?:\/.*)?$/i;
    

    See the regex101 demo.

    const regexExp = /^user\/[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}(?:\/.*)?$/i;
    
    [
      "user/a24a6ea4-ce75-4665-a070-57453082c256",
      "user/a24a6ea4-ce75-4665-a070-57453082c256/photo",
      "user/a24a6ea4-ce75-4665-a070-57453082c256asdasd"
    ].forEach(s =>
      console.log(`${s} --> ${regexExp.test(s)}`)
    );