Trichome


Convoluted way using .exec() and a loop:

var months = [ "January", "February", "March",     "April",   "May",      "June",
               "July",    "August",   "September", "October", "November", "December" ];
var isoRegex = /(\[\[)?\b([12]\d\d\d)(\]\])?-(\[\[)?(0[1-9]|1[0-2])-([0-3]\d)\b(?!-)(\]\])?/;
var lastIsoRegexFoundAt = 0;
var isoRegexResult = isoRegex.exec(pageSource);

while (isoRegexResult)
{
    if (formattingAmericanStyle)
        reformattedDate = months[isoRegexResult[5] - 1] + " " + (isoRegexResult[6] - 0) + ", " + isoRegexResult[2];
    else
        reformattedDate = (isoRegexResult[6] - 0) + " " + months[isoRegexResult[5] - 1] + " " + isoRegexResult[2];
    
    var regexFoundAt = pageSource.search(isoRegex, lastIsoRegexFoundAt);
    if (regexFoundAt != -1)
    {
        pageSource = pageSource.substr(0, regexFoundAt) + reformattedDate + pageSource.substr(regexFoundAt + isoRegexResult[0].length);
        isoRegexResult = isoRegex.exec(pageSource.substr(regexFoundAt + reformattedDate.length));
    }
    else
    {
        isoRegexResult = null;
    }
    lastIsoRegexFoundAt = regexFoundAt;
}


Simpler way using .replace() with a function:

var months = [ "January", "February", "March",     "April",   "May",      "June",
               "July",    "August",   "September", "October", "November", "December" ];
var isoRegex = /(\[\[)?\b([12]\d\d\d)(\]\])?-(\[\[)?(0[1-9]|1[0-2])-([0-3]\d)\b(?!-)(\]\])?/g;

pageSource = pageSource.replace( isoRegex, function(date, a,year,b,c,month,day,d)
{
    if (formattingAmericanStyle)
        return months[month-1] + " " + (day-0) + ", " + year;
    else
        return (day-0) + " " + months[month-1] + " " + year;
});


Adding some "look-behind" to ensure dates in links aren't changed:

var months = [ "January", "February", "March",     "April",   "May",      "June",
               "July",    "August",   "September", "October", "November", "December" ];
var isoRegex = /(\[\[)?\b([12]\d\d\d)(\]\])?-(\[\[)?(0[1-9]|1[0-2])-([0-3]\d)\b(?!-)(\]\])?/g;

pageSource = pageSource.replace( isoRegex, function(date, a,year,b,c,month,day,d, pos,string)
{
    // Don't touch dates inside links, template names, URLs, or HTML tags.
    // Or if "date" ends a longer ID number like 33-2539-55-1987-10-25.
    //
    var pat = /\[\[[^|\]]*$|\{\{[^|}]*$|[:\/%][^\s|>]+$|<[^>]*$|-$/;
    if (string.substring(pos-260,pos).search(pat) >= 0)
        return date;

    if (formattingAmericanStyle)
        return months[month-1] + " " + (day-0) + ", " + year;
    else
        return (day-0) + " " + months[month-1] + " " + year;
});

Leave a Reply