Obtain substrings from matching regex

I have this regex

const regex = new RegExp(/^\${[a-z][a-z0-9_]*}\/\${[a-z][a-z0-9_]*}$/, 'g');

that matches the string "${total_123}/${number_items}". Next, I want to extract the substrings total123 and number_items and set them as

const numerator = total_123 and const denominator = number_items. I’m not exactly sure how to do so.

>Solution :

const regex = new RegExp(/^\${([a-z][a-z0-9_]*)}\/\${([a-z][a-z0-9_]*)}$/, 'g');
const string = "${total_123}/${number_items}";

const matches = string.match(regex);

if (matches) {
  const numerator = matches[1];
  const denominator = matches[2];

  console.log("numerator:", numerator); // "total_123"
  console.log("denominator:", denominator); // "number_items"

The parts enclosed in parentheses in the regex pattern represent groups. These groups can be individually captured using matches array, with the elements at index 1 and 2. This allows you to capture the expressions enclosed in parentheses separately.

Leave a Reply