'Intermediate Algorithm Scripting: Search and Replace
Question
Perform a search and replace on the sentence using the arguments provided and return the new sentence.
First argument is the sentence to perform the search and replace on.
Second argument is the word that you will be replacing (before).
Third argument is what you will be replacing the second argument with (after).
Note
Preserve the case of the first character in the original word when you are replacing it. For example if you mean to replace the word "Book" with the word "dog", it should be replaced as "Dog".
function myReplace(str, before, after) {
let regex = /^([A-Z])/
let regexx = /^([a-zA-Z])/
let testBefore = regex.test(before);
let matchFirst = after.match(regexx);
let matchFirsti = matchFirst.toString();
if (testBefore == true) {
let correctFirstLetter = matchFirsti.toUpperCase();
let newAfter = after.replace(regexx, correctFirstLetter);
return str.replace(before, newAfter);
} else {
let altCorrectFirstLetter = matchFirsti.toLowerCase();
let newAfter = after.replace(regexx, altCorrectFirstLetter);
return str.replace(before, newAfter);
}
}
console.log(myReplace("A quick brown fox jumped over the lazy dog", "jumped", "leaped"));
console.log(myReplace("His name is Tom", "Tom", "john"));
My Question
- My code seems to be replacing incorrectly. It provides the correct letter, followed by a comma and then the full replacement word. It is absolutely bizarre. Please help me identify the error here?
Solution 1:[1]
Your solution seems to be too complicated to me + has some unnecessary duplication.
Here is a suggestion:
let isUpperCase = function(letter) {
return letter.toUpperCase() === letter;
}
let myReplace = function(text, before, after) {
let correctLetter = isUpperCase(before[0]) ? after.charAt(0).toUpperCase() : after.charAt(0).toLowerCase();
let newAfter = correctLetter + after.substr(1);
return text.replace(before, newAfter);
}
console.log(myReplace("A quick brown fox jumped over the lazy dog", "jumped", "Leaped"));
console.log(myReplace("His name is Tom", "Tom", "john"));
Solution 2:[2]
I've tried to make mine simpler, I know I'm still green at these, but it works.
function myReplace(str, before, after) {
if (before[0].toUpperCase() === before[0]) {
return str.replace(before, after[0].toUpperCase() + after.slice(1));
} else {
return str.replace(before, after.toLowerCase());
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Anar Salimkhanov |