Replace Letters with Position in Alphabet - Regex

Add a condition in your loop:

Replace:

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

with:

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

console.log(alphabetPosition('n8_ovuu&'));

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))
        .substr(1);
}

console.log(alphabetPosition('n8_ovuu&'));


You're getting zeros because some of the characters (like _ and &) don't match the alphabet. When .indexOf() can't find a match, it returns -1. You then gets + 1 added to it, making it zero.

You can either add those characters to the alphabet or you might want to ignore those by simply adding an if clause.

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

To tell your regular expression to filter non-alphabet characters, replace \W with an explicit inverted character range [^a-zA-Z].

console.log("abc_def".replace(/[^a-zA-Z]/, ''));