Created
January 9, 2018 09:43
-
-
Save dbrockman/2db3154adc6e52a5b680dfb3451c63ab to your computer and use it in GitHub Desktop.
Remove all occurrences of a substring from a string
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function removeSubstring(string, substring) { | |
let result = string; | |
if (substring) { | |
let index = result.indexOf(substring); | |
while (index >= 0) { | |
result = result.substring(0, index) + result.substring(index + substring.length); | |
index = result.indexOf(substring, index); | |
} | |
} | |
return result; | |
} | |
function removeSubstrings(string, substrings) { | |
return substrings.reduce(removeSubstring, string); | |
} | |
function replaceSubstring(string, substring, replacement) { | |
let result = string; | |
if (substring) { | |
let index = result.indexOf(substring); | |
while (index >= 0) { | |
result = result.substring(0, index) + replacement + result.substring(index + substring.length); | |
index = result.indexOf(substring, index + replacement.length); | |
} | |
} | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment