1

I have a string that contains dates in the mm-yyyy; yyyy-mm; yyyy-mm-dd, etc. formats. The goal is to convert the month portion of the date substring into a roman numeric notation, e.g.

12-2018 ... 2018-12-28

to be converted into

XII-2018 ... 2018-XII-28

I use this function to convert conventional into roman digits:

// https://stackoverflow.com/questions/9083037/convert-a-number-into-a-roman-numeral-in-javascript
function romanize(num) {
  var lookup = {M:1000,CM:900,D:500,CD:400,C:100,XC:90,L:50,XL:40,X:10,IX:9,V:5,IV:4,I:1},roman = '',i;
  for ( i in lookup ) {
    while ( num >= lookup[i] ) {
      roman += i;
      num -= lookup[i];
    }
  }
  return roman;
}

The regex used to find the month substring is

var re = /(19|20\d{2})\b-(\d{2})/g;

First parenthesized match ($1) is the year 19YY or 20YY only. The second ($2) is the month substring. The problem is that I cannot pass $2 as a parameter, i.e.

string = string.replace(re, "$1-" + romanize($2));

1 Answers1

1

Probably what you are looking for is something like:

string.replace(re, function(match, p1, p2) {
    return p1+'-'+romanize(p2);
});

I hope it helps you!

EDIT: The meaning of the arguments in function() is positional so the first argument will be the entire match, the second the first parenthesized match, the third the second parenthesized match...

You can also pass a function which already exists to replace like:

function rep(match, p1, p2) {
    p1+'-'+romanize(p2);
}
string.replace(re, rep);

EDIT2: To find the docs copy the quoted text and open the link in other tab of your browser and press ctrl+f in this page, paste the text below, and press ctrl+g one time, you will be in the section where this is explained.

Specifying a function as a parameter

Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace

sergiotarxz
  • 520
  • 2
  • 14
  • @ sergiotarxz - thank you very much! Yes your example is just what I was looking for, but can you please explain how it works - are the parameters of the anonymous function reserved key words, how can I find any documentation about this? – Samo Zaparola Dec 28 '18 at 22:11
  • I have changed the answer to meet your questions. – sergiotarxz Dec 29 '18 at 09:29