Javascript String#constantize and String#parse – Useful Extensions 26 and 27

Here are two extensions to the String class that I’ve found quite useful. constantize and parse. They are in CoffeeScript because JavaScript fills me with a growing disgust.

String::constantize = () ->
  if this.match /[A-Z][A-z]*/
    eval("var that = #{this}")
    that
  else
    undefined
 
String::parse = () ->
  try
    return JSON.parse(this)
  catch e
    return this

constantize is based on the ActiveSupport method. It transforms a string that represents the name of a class into a reference to that class. It uses eval to accomplish this, but until JavaScript gets more extensive reflection capabilities it’s probably the best we can do.

Parse is a useful way to convert the string into a raw JavaScript type if possible, otherwise it returns just the string itself. For example if I have a string "false", "false".parse() will return the JavaScript value false. Likewise '{"a": 7}'.parse() will return a JavaScript object with a property a that has the value 7.

Pretty sweet.

Leave a Reply

Your email address will not be published. Required fields are marked *