Tips and Tricks

Novel use of $translate
The $translate function can be used in a backwards manner to reformat certain kinds of strings.

Traditionally, its functionality is explained in terms of replacing specific characters in a string with other characters. The first argument is normally a variable and the second and third arguments are normally static strings, like this.

But it can also be used the other way around, with the first two arguments being static strings and the third argument being a variable like this:

In this example the contents of the variable date are transformed from the format of the second argument in to that of the first argument.

This method works because $translate replaces any occurrence of a character in argument 1 that is in argument 2 with the corresponding character in argument 3. Looking at the first character in argument 1, which is a D, this is replaced because there is a D in the second argument. The D in the second argument is the 7th character and so the 7th character of the date variable is used to replace it.

Note that it is necessary for each match character in argument 2 to be unique, so Mm cannot be used both for the month part and the minutes part, neither can MM be used. The trick would work just as well if any arbitrary but unique letters or numbers were used, but is much harder to read if they are not chosen with care.

is functionally equivalent to the example above but is obviously totally unintelligible.