Jon M. Langel Jon M. Langel - 1 year ago 174
Javascript Question

Replace Letters with Position in Alphabet - Regex

This challenge's description is to take a string and replace the letters with the letters position in the alphabet starting from 1-index. Requires you to skip all non-characters including whitespace.

function alphabetPosition(text) {
var result = [];
var alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j",
"k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
"w", "x", "y", "z"]
text = text.replace(/\W*\d+/g, '').toLowerCase().split('');
for (var i = 0; i < text.length; i++)
result.push(alphabet.indexOf(text[i]) + 1);
return result.join(' ');

My problem is when it comes to random tests, the input will contain digits and non word characters but the Regex isn't recognizing it. The input is
and the output/error is
Expected: '14 15 22 21 21', instead got: '14 0 15 22 21 21 0'

The problem lies in the Regex, but I can't figure it out. If you have any idea I would appreciate the help!

Answer Source

Add a condition in your loop:


for (var i = 0; i < text.length; i++) 
  result.push(alphabet.indexOf(text[i]) + 1);


for (var i = 0; i < text.length; i++) {
  var j = alphabet.indexOf(text[i]) + 1;
  if (j) result.push(j);

Note that you can define the alphabet as a string instead of an array, without any change to the above loop:

var alphabet = 'abcdefghijklmnopqrstuvwxyz';

Functional Programming solution - without RegEx

Here is an ES6 code solution which chains method upon method to return the result in one return statement:

function alphabetPosition(text) {
  return text.toLowerCase().split('')
        .filter( c => c >= 'a' & c <= 'z' )
        .map( c => c.charCodeAt(0) - 'a'.charCodeAt(0) + 1)
        .join(' ');


Functional Programming solution - with RegEx

function alphabetPosition(text) {
  return text.toLowerCase().replace(/[^a-z]/g, '')
        .replace(/./g, ([c]) => ' ' + (c.charCodeAt(0) - 'a'.charCodeAt(0) + 1))


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download