- You will create a program that takes a sentence, then search for a word in it and replaces it for a new one while preserving the uppercase if there is one.
- Find the index where
beforeis in the string.
- Check first letter case.
- Strings are immutable, you will need to save the edits on another variable, even if you must reuse the same one just to make it look like the changes where done using just that one variable.
Solution ahead!
function myReplace(str, before, after) {
// Find index where before is on string
var index = str.indexOf(before);
// Check to see if the first letter is uppercase or not
if (str[index] === str[index].toUpperCase()) {
// Change the after word to be capitalized before we use it.
after = after.charAt(0).toUpperCase() + after.slice(1);
}
// Now replace the original str with the edited one.
str = str.replace(before, after);
return str;
}function myReplace(str, before, after) {
//Create a regular expression object
var re = new RegExp(before,"gi");
//Check whether the first letter is uppercase or not
if(/[A-Z]/.test(before[0])){
//Change the word to be capitalized
after = after.charAt(0).toUpperCase()+after.slice(1);
}
//Replace the original word with new one
var newStr = str.replace(re,after);
return newStr;
}- Read comments on program.
If you found this page useful, you can give thanks by copying and pasting this on the main chat: thanks @Rafase282 thanks @coded9
NOTE: Please add your username only if you have added any relevant main contents to the wiki page. (Please don't remove any existing usernames.)