Mugg84
Mugg84

Reputation: 685

Splice in function doesn't change a character as expected

I've been working for a while on this function but i cannot figure out why even if I'm using .splice() I don't get a modified array. I'm providing the index at which to start changing the array "i", the number of elements to remove "1" and the element to add "str[i]".

function wave(str) {
  let result = [];
  for (let i = 0; i < str.length; i++) {
    if ((/[a-z]/ig).test(str[i])) {
      let st = str.split("").splice(i, 1 , str[i].toUpperCase());
      result.push(st);
    }
  }
 return result;

}


console.log(wave('hello')); // expected ["Hello", "hEllo", "heLlo", "helLo", "hellO"];
console.log(wave("two words")); // ["Two words", "tWo words", "twO words", "two Words", "two wOrds", "two woRds", "two worDs", "two wordS"];

Upvotes: 3

Views: 143

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386654

Array#splice returns the removed item/s. You need to keep the array - and remove and add the new item.

The regular expression does not need to be wrapped with parenthesis for accessing the RegExp#test method.

Before pushing to array, you need to take Array#join for getting a single string.

function wave(str) {
    let result = [];
    for (let i = 0; i < str.length; i++) {
        if (/[a-z]/ig.test(str[i])) {
            let st = str.split("");
            st.splice(i, 1, str[i].toUpperCase());
            result.push(st.join(''));
        }
    }
    return result;
}

console.log(wave('hello')); // expected ["Hello", "hEllo", "heLlo", "helLo", "hellO"];
console.log(wave("two words")); // ["Two words", "tWo words", "twO words", "two Words", "two wOrds", "two woRds", "two worDs", "two wordS"];
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 7

Related Questions