javascriptregexregex-group

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)

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


    One alternative workaround is using eval but use it only when you can trust that original url will not contain any malicious JS code from external users:

    let cUrl = eval(url.replace(/(.+=)(\d+):(\d+)$/, '"$1" + ($2*60 + $3) + "s"'));