File tree Expand file tree Collapse file tree 1 file changed +29
-0
lines changed Expand file tree Collapse file tree 1 file changed +29
-0
lines changed Original file line number Diff line number Diff line change 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.
You can’t perform that action at this time.
0 commit comments