How to change every other character in my string to the value "K"?

Viewed 35

I want to change every other character (starting from the second) in my string to the value "K".

The variable name which I am using is shown to be "deprecated" in VS Code.

Here is my code:

let name = "mellow";
for (x = 0; name.length > x; x++) {
  if (x % 2 != 0) {
    name[x] = "K"
  }
}
console.log(name);

2 Answers

First, you split the string to convert it into an array, with an empty separator. Then, you map its items (characters) to either themselves or K, depending on the result of `index % 2.

let input = "AAAAAAAAAAAAAAAA";
console.log(input.split("").map((item, index) => (index % 2 === 0) ? item : "K").join(""));

In JavaScript, strings are immutable. You can't update their values by indices. To make it work, you could build another string by concatenating characters to it. However, string concatenation is expensive.

Instead, we could push the required characters to an array and join them at the end.

let name = "mellow";
const result = [];

for (x = 0; name.length > x; x++) {
  if (x % 2 != 0) {
    result.push("K");
  } else {
    result.push(name[x]);
  }
}

console.log(result.join(""));

The mentioned script could be written as the following as well.

let name = "mellow";

let result = [...name].map((char, index) => index % 2 !== 0 ? "K" : char).join("");

console.log(result);

Related