Home > OS >  Replacing alternative letters in a string to either "!" or "?"
Replacing alternative letters in a string to either "!" or "?"

Time:09-20

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 =(

    function change(str) {
        newString = str.split("");
        for (let i = 1; i < newString.length - 1; i =2) {
                newString[i] = "!";
                //newString[i] = "?";    
         }    
         return(newString.join("")); }

console.log(change("Teddy")); should return T!d?y

CodePudding user response:

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

  • Declare your variables - doing 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)

CodePudding user response:

You can add a check and update variable to be replaced.

Few pointers:

  • When looping, you will have to loop till last character. 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"));

  • Related