Skip to content

Instantly share code, notes, and snippets.

@StevenXL
Created June 14, 2015 21:43
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 StevenXL/0888d2a2337742ba40f8 to your computer and use it in GitHub Desktop.
Save StevenXL/0888d2a2337742ba40f8 to your computer and use it in GitHub Desktop.
FreeCodeCamp Bonfire - Search and Replace
function replace(str, before, after) {
// make sure before and after are the same case
after = duplicateCase(before, after);
// use RegExp object with global setting on
var searchFor = new RegExp(before, 'g');
return str.replace(searchFor, after);
}
function duplicateCase(sourceWord, modifiableWord) {
// figure out the case of both words
var sourceCase = isUpperCase(sourceWord);
var modifiableCase = isUpperCase(modifiableWord);
// if they are the same case, then return the second argument
if (sourceCase === modifiableCase) {
return modifiableWord;
}
else if (sourceCase && !modifiableCase) {
// source is uppercase, modifiable is lower case
return upperCaseWord(modifiableWord);
}
else {
// source must be lower case and modifiable upper case
return lowerCaseWord(modifiableWord);
}
}
function isUpperCase(word) {
// return True if the first letter of the argument is upperCase
// false otherwise
if (word.charCodeAt(0) >= 65 && word.charCodeAt(0) <= 90) {
return true;
}
else {
return false;
}
}
function upperCaseWord(word) {
var upperCaseLetter = word[0].toUpperCase();
return upperCaseLetter + word.slice(1);
}
function lowerCaseWord(word) {
var lowerCaseLetter = word[0].toLowerCase();
return lowerCaseLetter + word.slice(1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment