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()));

1
  • 1
    You can use the RegExp constructor stackoverflow.com/questions/494035/… 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. Commented Nov 8, 2019 at 22:43

2 Answers 2

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'));

Sign up to request clarification or add additional context in comments.

Comments

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));
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.