Skip to content

Commit 4f1223a

Browse files
committed
Merge pull request coffeescript-cookbook#140 from Data-Meister/master
Add new chapter: replacing sub-strings
2 parents 23eb90c + fdb756a commit 4f1223a

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
---
2+
layout: recipe
3+
title: Replacing Sub-Strings Within a String
4+
chapter: Strings
5+
---
6+
## Problem
7+
8+
You want to replace a sub-string with a new sub-string.
9+
10+
## Solution
11+
12+
Split the string using the sub-string you want to remove as a delimiter. Then re-join using the new sub-string as the delimiter.
13+
14+
{% highlight coffeescript %}
15+
"Orange is the new Black".split("Orange").join("Pink")
16+
# => "Pink is the new Black"
17+
18+
"I am so sad. I cannot believe how sad I am today!".split("sad").join("happy")
19+
# => "I am so happy. I cannot believe how happy I am today!"
20+
21+
"I am not a crook.".split("not ").join("")
22+
# => "I am a crook."
23+
{% endhighlight %}
24+
25+
## Discussion
26+
27+
You can also use regexes. If you're matching an exact string, this way is simpler and 10x faster.
28+
29+
If you use regexes, remember that you must escape certain characters.

0 commit comments

Comments
 (0)