I'm trying to write a function that accepts a string and the string will be returned in a 'waved' version inside an array:
wave("stack") => ["Stack","sTack", "stAck", "staCk", "stacK"]
I wrote this code, but there's a problem when I have a doubled letter in the string:
function wave(word){
let arr = []
word.split("").map(c=> arr.push(word.replace(c, c.toUpperCase())))
return arr
}
console.log(wave("hello"))
wave("hello") gives me ["Hello", "hEllo", "heLlo", "heLlo", "hellO"]
Notice that index 2 and index 3 are the same, index 3 is suppose to be "helLo", not "heLlo". Why is that? How can I fix this?
The problem happened due to the way the call of replace is being made. It was always replacing the first instance of l. The following code should work.
function wave(word){
let arr = []
word.split("").map((c, i) => {
let parta = word.substring(0, i);
let partb = word.substring(i + 1);
arr.push(parta + c.toUpperCase() + partb);
});
return arr
}
console.log(wave("stack"));
console.log(wave("hello"));
Since you are already using a map there is no reason to use arr.push. Secondly you can use index of the map function and string substr method.
This line will first create a sub string using characters from 0 till the index concat with the uppercase letter then remaining string
function wave(word) {
return word.split("").map(function(c, index) {
return word.substr(0, index) + c.toUpperCase() + word.substr(index + 1);
})
}
console.log(wave("hello"))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With