3

I am trying to change the characters of a string using for loop. My aim is to change each character with the following one. For example a should be converted to b, b is to c and finally z to a, etc. I have written the following code but it doesn't work.

function LetterChanges(str) { 
    var char = "abcdefghijklmnoprstuvyz";
    for(var i = 0; i < char.length; i++) {
        var newStr = str.replace(/char[i]/gi, char[i + 1]); // the problem is here 
    }
    return newStr; 
}
   
// keep this function call here 
console.log(LetterChanges(readline()));
ggorlen
  • 26,337
  • 5
  • 34
  • 50
  • 1
    You can use the RegExp constructor https://stackoverflow.com/questions/494035/how-do-you-use-a-variable-in-a-regular-expression but you have an issue at the end of your loop, (i+1 won't be a valid index anymore), plus if you fix that, you will replace everything with z. – ASDFGerte Nov 08 '19 at 22:43

2 Answers2

4

You could find a letter and replace with a function.

function LetterChanges(str) {
    var char = "abcdefghijklmnoprstuvyz";
    return str.replace(/[a-z]/gi, c => char[char.indexOf(c) + 1] || char[0]);
}

console.log(LetterChanges('foobar'));
Nina Scholz
  • 323,592
  • 20
  • 270
  • 324
0

in a single row:

const LetterChanges = (str=‘’) => String.fromCharCode(...[...str].map(c => c.charCodeAt(0) +1));

or if you prefer:

function LetterChanges(str = ‘’) {
    return String.fromCharCode(...[...str].map(c => c.charCodeAt(0) +1));
}
Andrew-io
  • 1
  • 3