Tell us what’s happening:
My solution to replacing the ‘before’ with the ‘after’ in a ‘str’ is below. I wanted to know if it could be shortened any to fewer lines, like if i can do more than 1 of the array methods on 1 line or not. I had to makeup 3 dummy variables just to save each step to be used in the next step…but it doesnt seem right to need to do that. I was hoping I could do like: d.shift().unshift( c) and/or after[0].toUpperCase().split("") to combine steps but i get errors…?
I’m having a hard time with array methods in terms of when I need to assign them to a new variable vs when they automatically update the existing array i.e. (arr.pop(“hi”) --automatically updates the arr with the entry “hi”…vs let a = arr.join("") --requires a new variable assignment to work). I was told before u just need to memorize which array method needs a variable assigned to work and which doesn’t, but as I said it looks ridiculous having to makeup all these dummy variables to relay 1 line’s ouput into the next line’s input.
I checked the other answers, i’d like to just get ‘this way’ cleaned up as much as possible.
Your code so far
function myReplace(str, before, after) {
let after2 = after
//if before is capitalized, capitalize after by making into array
if (before[0].match(/[A-Z]/)) {
let c = after[0].toUpperCase()
let d = after.split("")
d.shift()
d.unshift(c)
after2 = d.join("")
}
//replace before with after in the str
return str.replace(before,after2)
}
console.log(myReplace("A quick brown fox Jumped over the lazy dog", "Jumped", "leaped"));
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36.
Challenge: Search and Replace
Link to the challenge: