Skip to content

Commit 347b83b

Browse files
committed
add Replacing substrings recipe to Regular Expressions chapter
1 parent 050f2dd commit 347b83b

File tree

2 files changed

+39
-1
lines changed

2 files changed

+39
-1
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
---
2+
layout: recipe
3+
title: Replacing substrings
4+
chapter: Regular Expressions
5+
---
6+
## Problem
7+
8+
You need to replace a portion of a string with another value.
9+
10+
## Solution
11+
12+
Use the JavaScript `replace` method. `replace` matches with the given string, and returns the edited string.
13+
14+
The first version takes 2 arguments: _pattern_ and _string replacement_
15+
16+
{% highlight coffeescript %}
17+
"JavaScript is my favorite!".replace /Java/, "Coffee"
18+
# => 'CoffeeScript is my favorite!'
19+
20+
"foo bar baz".replace /ba./, "foo"
21+
# => 'foo foo baz'
22+
23+
"foo bar baz".replace /ba./g, "foo"
24+
# => 'foo foo foo'
25+
{% endhighlight %}
26+
27+
The second version takes 2 arguments: _pattern_ and _callback function_
28+
29+
{% highlight coffeescript %}
30+
"CoffeeScript is my favorite!".replace /(\w+)/g, (match) ->
31+
match.toUpperCase()
32+
# => 'COFFEESCRIPT IS MY FAVORITE!'
33+
{% endhighlight %}
34+
35+
The callback function is invoked for each match, and the match value is passed as the argument to the callback.
36+
37+
## Discussion
38+
39+
Regular Expressions are a powerful way to match and replace strings.

wanted-recipes.md

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,6 @@ foo 1, 2, 3
8686

8787
* Searching for substrings # "foo bar baz".match(/ba./) # => [ 'bar', index: 4, input: 'foo bar baz' ]
8888
* Searching for substrings # "foo bar baz".search(/ba./) # => 4
89-
* Replacing substrings # "foo bar baz".replace( /ba./, 'foo') # => "foo foo baz"
9089

9190
## Networking
9291

0 commit comments

Comments
 (0)