admin管理员组

文章数量:1193729

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!

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!

Share Improve this question edited Nov 9, 2016 at 20:29 Jon Langel asked Nov 9, 2016 at 20:15 Jon LangelJon Langel 1771 gold badge2 silver badges11 bronze badges
Add a comment  | 

6 Answers 6

Reset to default 12

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]/, ''));

This works and is quite concise:

const data = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"£$%^&*()';

const result = data.toLowerCase().match(/[a-z]/g).map(c => c.charCodeAt(0) - 96).join(' ');

console.log(result);

You could use an object for the indices of a letter. If no one is fount, take a default value.

function alphabetPosition(text) {
    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"],
        object = {};

    alphabet.forEach(function (a, i) {
        object[a] = i + 1;
    });
    return text.replace(/\W*\d+/g, '').toLowerCase().split('').map(function (a) {
        return object[a] || 0;
    }).join(' ');
}

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

Hey this worked for me.

const alphabetPosition = (text) => {
    // First isolate the characters in the string using split method, and then map them.
    const result = text.split('').map(a => parseInt(a, 36) - 9)
        .filter(a => a >= +1).join(' ')

    console.log(result)
  }

alphabetPosition(text)
import string

def alphabet_position(text):
  text = text.lower
  result = ""
  for x in text():
     if x.isalpha():
        result = result + str(string.ascii_lowercase.index(x) + 1) + " "
    else:
        pass
  result = result.strip()
  return result

本文标签: javascriptReplace Letters with Position in AlphabetRegexStack Overflow