Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 n8_ovuu& 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!

like image 752
Jon Langel Avatar asked Nov 09 '16 20:11

Jon Langel


People also ask

Which below RegEx is applicable for alphabets?

[A-Za-z] will match all the alphabets (both lowercase and uppercase).

Which function is used to replacing pattern in string?

The REGEXREPLACE( ) function uses a regular expression to find matching patterns in data, and replaces any matching values with a new string.


2 Answers

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&'));
like image 106
trincot Avatar answered Sep 20 '22 17:09

trincot


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]/, ''));
like image 41
Soviut Avatar answered Sep 19 '22 17:09

Soviut