Programming languages have methods to cast integers to strings and strings to integers, but usually is had to find equivalents to parseInt(), a Javascript function that basically removes all non-numeric characters from a string and returns the resulting integer.
Today, while working on a Freemarker template, I had to convert strings like “40 ms.” and “128 px” to their respective integers 40 and 128. The solution I found is to use regular expressions, which are kind of tricky in Freemarker but can save you lots of time.
Example in Javascript:
-
console.log(parseInt("40 ms")) // outputs 40
-
console.log("40 ms".match(/^\d+/)[0]) // outputs 40
Same in Freemarker:
-
<#assign myInt = "40 ms."?matches("^(\\d+)(.*)")[0]?groups[1]>
Looks like even using regular expressions, in Freemarker we need to match the whole string with groups to separate the number from the rest. Thus, this will work only if the number is at the beginning of the string, which was the initial requirement in my case.
