Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

CoffeeScript converts strings into small case


May 09, 2021 CoffeeScript


Table of contents


Convert strings to small case

Problem

You want to convert the string into a small case.

Solution

The toLowerCase() method of String using JavaScript:

"ONE TWO THREE".toLowerCase()
# => 'one two three'

Discuss

ToLowerCase() is a standard JavaScript method. Don't forget to put parentheses.

Grammar blocks

You can add some Ruby-like syntax block with the following shortcut:

String::downcase = -> @toLowerCase()
"ONE TWO THREE".downcase()
# => 'one two three'

The above code demonstrates two features of CoffeeScript:

  • Double colon: is a shortcut .prototype
  • The "at" character is a shortcut to the this.

The above code is compiled into javaScript code as follows:

String.prototype.downcase = function() {
  return this.toLowerCase();
};
"ONE TWO THREE".downcase();

Tip Although the above usage is common in Ruby-like languages, extensions to local objects are often considered bad in JavaScript. ( See: Maintain JavaScript: Don't modify objects you don't own; not? vil or not?