Tell us what’s happening: Please, find below my code so far. It’s working when the word to replace starts by capital letter indeed, but failing when it’s not. Any hint about what’s wrong with it?
Thanks in advance
Describe your issue in detail here.
Your code so far
function myReplace(str, before, after) {
let capitalL = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".split("");
if (str.search(before) != -1 && capitalL.indexOf(str[before[0]])) {
return str.replace(before, after.slice(0, 1).toUpperCase().concat(after.slice(1)));
}
return str.replace(before, after.toLowerCase())
}
myReplace("A quick brown fox jumped over the lazy dog", "jumped", "leaped");
myReplace("He is Sleeping on the couch", "Sleeping", "sitting")
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36
Challenge: Intermediate Algorithm Scripting - Search and Replace
My intention with that code was to check in the string if the first letter of the word that contains the argument before is a capital one, but I guess I’m wrong
I replaced it for the code below, but still same issue:
That is the only bit of your code which isn’t quite working.
Let’s break it down:
capitalL.indexOf(str[before[0]])
Let’s say the function is called as:
myReplace("He is Sleeping on the couch", "Sleeping", "sitting")
So, before[0] would be ‘S’, which would make str[before[0]] equal to str['S'], which doesn’t make any sense (i.e. it will return undefined). You don’t need to include str here at all. You are only checking if the first letter of before is a capital (i.e. it appears in capitalL).
Having corrected that, you also need to determine what kind of value indexOf will return when it looks for the letter ‘S’ in capitalL. If it finds it, it will return the index number where it is first found. If it doesn’t find it, it would return -1. So you want your condition to check that indexOf doesn’t return -1.