Use regex to check if first character of ‘before’ is capital and if so change. Then replace:
function myReplace(str, before, after) {
if (/[A-Z]/.test(before[0])) {
after = after.charAt(0).toUpperCase() + after.slice(1);
}
var newStr = str.replace(before, after);
return newStr;
}
myReplace("A quick brown fox jumped over the lazy dog", "jumped", "leaped");
After having to look up solutions for a few past exercises, it felt really good to reach the solution on my own for this exercise
function myReplace(str, before, after) {
var character = before.charAt(0);
if (character == character.toUpperCase()) {
after = after[0].toUpperCase() + after.slice(1);
}
if (character == character.toLowerCase()){
after = after[0].toLowerCase() + after.slice(1);
}
var newStr = str.replace(before, after);
return newStr;
}
myReplace("A quick brown fox jumped over the lazy dog", "jumped", "leaped");
function myReplace(str, before, after) {
//Capitalize After if before is cap
if (before[0] === before[0].toUpperCase()){
after = after.charAt(0).toUpperCase() + after.slice(1);
}
//Regex to grab the value in the word
var re = new RegExp(before,"g");
str=str.replace(re, after);
return str;
}
myReplace("A quick brown fox jumped over the lazy dog", "Jumped", "leaped");
I am just learning so I compared the charCodeAt() results
function myReplace(str, before, after) {
if(before.charCodeAt(0) < 93 && after.charCodeAt(0) > 93){
//replacing lower case with upper case
// i should do the reverse but there's none in the tests
var x = after.charCodeAt(0) - 32;
var y = String.fromCharCode(x);
after = after.replace(/[a-z]/,y);
}
var words = str.split(" ");
for (i=0; i<words.length; i++){
if (words[i] == before){
words.splice(i,1);
words.splice(i, 0, after);
words = words.join();
words = words.replace(/,/g, " ");
}
}
return words;
}
myReplace("Let us get back to more Coding", "Coding", "algorithms");
function myReplace(str, before, after) {
// change string into array and add variable that store index of "before" argument
let arr = str.split(' '),
delIndex;
// loop array, search delIndex and make condition if first letter is upper case
arr.forEach((item,index) => {
if(item === before) {
delindex = index;
if (before[0] === before[0].toUpperCase()) {
after = after.replace(after[0], after[0].toUpperCase());
}
}
});
//raplace before => after
arr.splice(delindex, 1, after);
return arr.join(' ');
}
myReplace("This has a spellngi error", "spellngi", "spelling");
Maybe this is not the most efficient code, but it works.