This
I'm able to return T!d!y. But i need T!d?y. I'm new to JS and I cant figure it out =(
This
I'm able to return T!d!y. But i need T!d?y. I'm new to JS and I cant figure it out =(
Use modulo to check whether the i being iterated over is one of the 3-7-11 sequence or the 1-5-9 sequence - then you can determine which character to insert.
function change(str) {
const arr = str.split("");
for (let i = 1; i < arr.length - 1; i += 2) {
arr[i] = i - 1 % 4 === 0
? "!"
: "?";
}
return arr.join("");
}
console.log(change("Teddy"));
Also remember
newString = without a const (or something) before it implicitly creates a global variable, which is very often not what you want.split returns an array; newString is not an accurate description of what the variable contains (perhaps instead call it arr or newArray or characters, or something like that)You can add a check and update variable to be replaced.
Few pointers:
i < arr.length - 1 will cause issues for certain scenarios.function change(str) {
const possibilities = [ "!", "?", "*" ];
let index = 0;
let newString = str.split("");
for (let i = 1; i < newString.length ; i += 2) {
newString[i] = possibilities[index % possibilities.length];
index++
}
return (newString.join(""));
}
console.log(change("Teddy"));
console.log(change("Javascript"));