In python there's function replace(old, new) which replaces "old" to "new" in some string, is there any function like this or any way to do it in Crystal?
Asked
Active
Viewed 435 times
1 Answers
7
From the Crystal-lang api docs you can use the .sub function:
"hello yellow".sub("ll", "dd") # => "heddo yellow"
Source: https://crystal-lang.org/api/0.23.1/String.html
NOTE: This function only replaces the first occurrence of the search string. There also appears to be a version of the sub function that allows you to pass a regex string which should allow you to grab all occurrences of a particular string.

Tim Tutt
- 184
- 7
-
3[String#gsub](https://crystal-lang.org/api/0.23.1/String.html#gsub%28string%3AString%2Creplacement%29-instance-method) to replace all occurrences. – Vitalii Elenhaupt Dec 18 '17 at 15:35