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

CoffeeScript replaces substrings


May 09, 2021 CoffeeScript


Table of contents


Replace substrings

Problem

You need to replace part of the string with another value.

Solution

Use JavaScript's replace method. It matches a given string and returns the edited string.

The first version requires two parameters: pattern and string replacement

"JavaScript is my favorite!".replace /Java/, "Coffee"
# => 'CoffeeScript is my favorite!'

"foo bar baz".replace /ba./, "foo"
# => 'foo foo baz'

"foo bar baz".replace /ba./g, "foo"
# => 'foo foo foo'

The second version requires two parameters: the pattern and the callback function

"CoffeeScript is my favorite!".replace /(\w+)/g, (match) ->
  match.toUpperCase()
# => 'COFFEESCRIPT IS MY FAVORITE!'

Each match requires a callback function to be called, and the matching value is passed to the callback function as an argument.

Discuss

Regular expressions are a powerful way to match and replace strings.