Skip to content

Instantly share code, notes, and snippets.

@LaurelineP
Created March 28, 2019 09:53
Show Gist options
  • Save LaurelineP/fab0f89b0d901679a431b0bd9a17256a to your computer and use it in GitHub Desktop.
Save LaurelineP/fab0f89b0d901679a431b0bd9a17256a to your computer and use it in GitHub Desktop.
Search and replace - algorithm created by LaurelineP - https://repl.it/@LaurelineP/Search-and-replace-algorithm
function myReplace(str, before, after ) {
/*
* 1. Check if the old word has its first letter in a capital or not:
* - if yes : return the new word with a capital on the first letter
* - if no : return the new word as it is
*/
let newStr = /^[A-Z]/.test( before[0] )
? `${ after.substring( 0, 1 ).toUpperCase()}${ after.substring( 1 ) }`
: after;
/* 2. Replace ( oldWord, newWord ) */
return str.replace( before, newStr );
}
myReplace("Let us get back to more Coding", "Coding", "algorithms")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment