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

CoffeeScript string interpolation


May 09, 2021 CoffeeScript


Table of contents


String interpolation

Problem

You want to create a string that contains text that reflects a CoffeeScript variable.

Solution

Use Ruby-like string interpolation in CoffeeScript instead of JavaScript string stitching.

Interpolation:

muppet = "Beeker"
favorite = "My favorite muppet is #{muppet}!"

# => "My favorite muppet is Beeker!"
square = (x) -> x * x
message = "The square of 7 is #{square 7}."

# => "The square of 7 is 49."

Discuss

CoffeeScript has a similar interpolation to Ruby's, and most expressions can be used in the Interpolation structure.

CoffeeScript supports putting multiple expressions with side effects into the interpolation structure, but it is recommended that you do not do so. Because only the last value of the expression is inserted.

# 可以这样做,但不要这样做。否则,你会疯掉。
square = (x) -> x * x
muppet = "Beeker"
message = "The square of 10 is #{muppet='Animal'; square 10}. Oh, and your favorite muppet is now #{muppet}."

# => "The square of 10 is 100. Oh, and your favorite muppet is now Animal."

Related tutorials

Ruby Tutorials