DEV Community

Muhammad Hamza
Muhammad Hamza

Posted on

2 1

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.

Solution

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)

Collapse
 
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.match(/[a-z]/i) 
      ? (x.charCodeAt(0) - 96).toString() 
      : '')
    .filter(x => x.length)
    .join(' ');
Enter fullscreen mode Exit fullscreen mode
Collapse
 
alekseiberezkin profile image
Aleksei Berezkin

That's faster than the original solution

Collapse
 
hijazi313 profile image
Muhammad Hamza

it's working correctly <3

Collapse
 
lionelrowe profile image
lionel-rowe

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(
    /[a-z]/g,
    ch => `${ch.codePointAt(0) - a + 1} `
)
Enter fullscreen mode Exit fullscreen mode
Collapse
 
capnmarius profile image
MariusLinders • Edited
const alphabetPosition = str =>
  [...str.toLowerCase()]
    .map(x => x.charCodeAt() - 96)
    .filter(x => x > 0)
    .join(" ")
Enter fullscreen mode Exit fullscreen mode

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay