Home > Back-end >  regex to find number after specific sub string
regex to find number after specific sub string

Time:04-10

I am struggling to figure out how to create a regex for this.

I have a string that look like this:

const stringOne = '12test';
const stringOne = '12test%today';
const stringOne = '12test%today 2';

My current regex is like this:

'test%today'.replace(/%today/g, formatDate());

> 'test01/01/2022'

Now I am trying to add logic to take the day and pass it to formatDate. I have tried many approaches with the latest being below

const string = '123test%today 2'
string.replace(/%today {i}/g, formatDate(string.match(/\d /g)));

> should be '123test03/01/2022'

CodePudding user response:

If I understand correctly, you're trying to pass the number after the "today" into your formateDate() function. To do that, you could use a capturing group ([ -]\d ) to capture the digit and its sign, followed by ? to make it optional. Then you can pass a function as the second argument to .replace() to access digit value from the capturing group (default it to 0 if it wasn't set), and pass that into formatDate() as a number using the unary plus operator :

const string = '123test%today 2';
const res = string.replace(/%today([ -]\d )?/g, (m, g=0) => formatDate( g));

CodePudding user response:

You should check groups concept in js string match func below.

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

It would be hlep.

  • Related