May 09, 2021 CoffeeScript
You need to replace part of the string with another value.
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.
Regular expressions are a powerful way to match and replace strings.