Last active
May 18, 2016 22:38
-
-
Save randallreedjr/beb6f978aad8a764562f40f1ca419d8e to your computer and use it in GitHub Desktop.
Javascript string replace
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
replaceText = function(string, oldText, newText) { | |
index = string.indexOf(oldText); | |
front = string.substring(0, index); | |
back = string.substring(index + oldText.length); | |
return front + newText + back; | |
}; | |
replaceTextGlobal = function(string, oldText, newText) { | |
while(string.indexOf(oldText) >= 0) { | |
string = replaceText(string, oldText, newText); | |
} | |
return string; | |
}; | |
console.log(replaceText("Randall","a","e")); | |
console.log(replaceTextGlobal("Randall","a","e")); | |
console.log(replaceText("Randall Reed","Randall","Randy")); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment