having fun with code

Equivalent of parseInt() in Freemarker

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:

  1. console.log(parseInt("40 ms")) // outputs 40
  2. console.log("40 ms".match(/^\d+/)[0]) // outputs 40

Same in Freemarker:

  1. <#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.

Related Posts:

Leave a Reply

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Additional comments powered by BackType

About the blog

This is a blog about development, focused mainly on Javascript but also other languages like python, shell scripts and more.

About the author

Eneko Alonso is a software engineer and UI developer with more than eight years of experience in software and web development. He lives in San Luis Obispo, California and works at LEVEL Studios.

Contact Info

Contact Info

PromoteJS

JavaScript JS Documentation