1

My challenge is to create a function that takes in a string and returns a new string with each character advanced 1 space of the alphabet. Ex: "hello" returns "ifmmp."

I haven't yet wrapped my code in a function. This will get me the first new character but I can't figure out how to move through the rest of the new characters.

var str = "hello";

var numStr = [];

for (var i = 0; i < str.length; i++) {

    numStr.push((str.charCodeAt(i) + 1));

}

var newStr = String.fromCharCode(numStr[0]);

//returns "i"
anothermh
  • 9,815
  • 3
  • 33
  • 52
adam.shaleen
  • 993
  • 3
  • 9
  • 20
  • You may use `+` operator to add strings so `'a' + 'b'` gives you `'ab'`. Use a for loop to build `newStr` like `var newStr = ''; for (var i = 0; ....) { newStr += String.fromCharCode(numStr[i]); }`. `newStr += x` is like `newStr = newStr + x` – csharpfolk Mar 08 '16 at 19:01

2 Answers2

2

You'll probably want to use fromCharCode(). Creating a function could look something like this:

JavaScript

var str = "hello";

function incrementStringLetters(s) {
    var newStr = "";
    for (var i = 0; i < s.length; i++) {
        newStr += String.fromCharCode(s.charCodeAt(i)+1);
    }
    return newStr;
}


console.log(incrementStringLetters(str))

Output

ifmmp

See it working here: https://jsfiddle.net/igor_9000/f0vy3h9v/

Hope that helps!

Adam Konieska
  • 2,805
  • 3
  • 14
  • 27
0

Another proposal with:

var str = "hello",
    newStr = str.split('').map(function (a) {
        return String.fromCharCode(a.charCodeAt(0) + 1);
    }).join('');

document.write(newStr);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392