Skip to content

Instantly share code, notes, and snippets.

@randallreedjr
Last active May 18, 2016 22:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save randallreedjr/beb6f978aad8a764562f40f1ca419d8e to your computer and use it in GitHub Desktop.
Save randallreedjr/beb6f978aad8a764562f40f1ca419d8e to your computer and use it in GitHub Desktop.
Javascript string replace
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