Home > front end >  Am I using this [^{\}] (?=}) regular expression correctly on TypeScript
Am I using this [^{\}] (?=}) regular expression correctly on TypeScript

Time:12-14

Hello I am trying to get the values surrounded by curly braces "{value}". I am using this regular expression [^{}] (?=}) correctly?

let url = "/{id}/{name}/{age}";

let params = url.match('[^{\}] (?=})');
if(params != null){

  params.forEach(param => {
    console.log(param);
  });
}

// expected output
id
name
age

//actual output
id

CodePudding user response:

By default the search stops after the first match.

You should use a regex literal delimited by slashes (like: /regex/), not a string delimited by quotes (like: 'string').

And then you should add the /g flag to the end of it, which means "global". This lets it search through the whole string to find all matches.

let url = "/{id}/{name}/{age}";

let params = url.match(/[^{\}] (?=})/g);
//                                   ^ do a global search
if(params != null){

  params.forEach(param => {
    console.log(param);
  });
}

From MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

The "g" after the regular expression is an option or flag that performs a global search, looking in the whole string and returning all matches.

  • Related