Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Regex $1, $2 data type conversion issue

I’m trying to add YouTube Video Bookmark somewhere.

If my YouTube Video URL is: ‘https://www.youtube.com/watch?v=xxxxxx&t=12:13’
Then it should be convert as format: ‘https://www.youtube.com/watch?v=xxxxxx&t=25s’

Basically I changes the timer format: 12:13 to 733s (12*60 + 13)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I can do it simple way.
But I want to do it in a single line with regex validation like:

let url = 'https://www.youtube.com/watch?v=xxxxxx&t=12:13';

console.log(url.replace(/(\d+)\:(\d+)/g, '$1$2'));

let cUrl = url.replace(/(\d+)\:(\d+)/g, `${Number($1)*60 + Number($2)}s`);
console.log(cUrl);

Browser Console Output:

enter image description here
enter image description here

Can some guide me why it’s showing the NaN?
What I’m doing wrong ?

>Solution :

As the comments suggest that you will need to use a use a replacer function instead of a replacement string since you want to convert capture groups to numbers, perform some arithmetic and append some text later.

Following code should work for you:

let url = 'https://www.youtube.com/watch?v=xxxxxx&t=12:13';
let cUrl = url.replace(/(\d+):(\d+)$/, function (m, g1, g2) {
   return Number(g1)*60 + Number(g2) + 's'; });

console.log(cUrl);
//=> https://www.youtube.com/watch?v=xxxxxx&t=733s
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading