-4

I am wondering how I would take a phrase that is an array in Javascript then make it so it would output letters next to the letter to show where in the alphabet they are such as Computer outputting 3C15o13m21u and so on. The phrase I have is shown in the code below

var firstPhrase = "Computers are the most fun way to use your time";
alert(firstPhrase);
Jeff Long
  • 5
  • 1
  • 3

1 Answers1

0

This should work:

var phrase = 'Computers are the most fun way to use your time';
console.log(phrase.replace(/([a-zA-Z)/g, function(c) {
    return (c.toUpperCase().charCodeAt(0) - 64) + c;
}));
Jon Taylor
  • 7,865
  • 5
  • 30
  • 55
Quagaar
  • 1,257
  • 12
  • 21
  • 1
    Care to explain to the OP rather than just blurting out a load of code? – Jon Taylor Nov 12 '16 at 22:07
  • The space character is converted to "-32 ". – JJJ Nov 12 '16 at 22:10
  • Yes, sure. This approach uses a RegExp to match every character in the input string and passes each match through a function that gets the upper case character code (with A = 65) and subtracts 64 to get an "Alphabet-Index" starting by 1. It then returns the code together with the match as the replacement. – Quagaar Nov 12 '16 at 22:14