DEV Community

Muhammad Hamza Hijazi
Muhammad Hamza Hijazi

Posted on

JavaScript Programming Problem

JavaScript Programming Problems Series

I am going to start a Programming test series where i will share commonly asked interview questions and their solutions for JavaScript developers.

Problem # 1

Replace With Alphabet Position

you are given a string, replace every letter with its's position in the alphabet, if the string has a value which is not an alphabet then ignore it. The Output should also be a String telling about the position of Alphabet.


function alphabetPosition(str){
str = str.split("");
  const position =[];
  const alpha = "abcdefghijklmnopqrstuvwxyz";
  for(let wo of str) {
    if (alpha.indexOf(wo)>=0) {
    position.push(alpha.indexOf(wo)+1, " ")
  return position.join("")
alphabetPosition("21a dsz")
Enter fullscreen mode Exit fullscreen mode

Top comments (5)

alinp25 profile image
Alin Pisica

I am not sure 100% about correctitude, I wrote it from my phone, but I hope it's doing well.

var alphabetPosition = str => str.split("").map(x => 
      ? (x.charCodeAt(0) - 96).toString() 
      : '')
    .filter(x => x.length)
    .join(' ');
Enter fullscreen mode Exit fullscreen mode
alekseiberezkin profile image
Aleksei Berezkin

That's faster than the original solution

hijazi313 profile image
Muhammad Hamza Hijazi

it's working correctly <3

lionelrowe profile image

Great idea for a series! But I think the question is a little under-specified. It'd be helpful to state that the output should also be a string (not an array), that alphabet places are 1-indexed, that each one must be followed by a space, and that you only need to handle lowercase Latin-alphabet letters without diacritics.

Anyway, here's my attempt:

const a = 'a'.codePointAt(0)
const alphaPos = str => str.replace(
    ch => `${ch.codePointAt(0) - a + 1} `
Enter fullscreen mode Exit fullscreen mode
capnmarius profile image
MariusLinders • Edited
const alphabetPosition = str =>
    .map(x => x.charCodeAt() - 96)
    .filter(x => x > 0)
    .join(" ")
Enter fullscreen mode Exit fullscreen mode