Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

toUpperCase() issue when I map

Tags:

javascript

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?

like image 781
Commando Avatar asked Dec 21 '25 19:12

Commando


2 Answers

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"));
like image 68
Md Johirul Islam Avatar answered Dec 23 '25 08:12

Md Johirul Islam


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"))
like image 26
brk Avatar answered Dec 23 '25 07:12

brk