Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Converting alphabets to Greek letters in JavaScript
Converting alphabets to Greek letters in JavaScript requires creating a mapping between English and Greek characters, then replacing each character accordingly.
Character Mapping
First, let's establish the mapping between English and Greek letters:
A=? (Alpha) B=? (Beta) D=? (Delta) E=? (Epsilon) I=? (Iota) K=? (Kappa) N=? (Eta) O=? (Theta) P=? (Rho) R=? (Pi) T=? (Tau) U=? (Mu) V=? (Upsilon) W=? (Omega) X=? (Chi) Y=? (Gamma)
Problem Statement
We need to create a function that converts English letters to their Greek equivalents where mappings exist, while preserving unmapped characters in lowercase.
Input:
const str = 'PLAYING';
Expected Output:
?l????g
Solution
const str = 'PLAYING';
const convertLang = (str) => {
const map = {
a: '?', b: '?', d: '?', e: '?',
i: '?', k: '?', n: '?', o: '?',
p: '?', r: '?', t: '?', u: '?',
v: '?', w: '?', x: '?', y: '?'
};
return str.replace(/./g, char => {
const lowerChar = char.toLowerCase();
if (map[lowerChar]) {
return map[lowerChar];
}
return lowerChar;
});
};
console.log(convertLang(str));
?l????g
How It Works
The function uses the replace() method with a regular expression /./g to match every character. For each character:
- Convert to lowercase using
toLowerCase() - Check if a Greek mapping exists in the
mapobject - Return the Greek letter if found, otherwise return the lowercase English letter
Testing with Multiple Examples
const convertLang = (str) => {
const map = {
a: '?', b: '?', d: '?', e: '?',
i: '?', k: '?', n: '?', o: '?',
p: '?', r: '?', t: '?', u: '?',
v: '?', w: '?', x: '?', y: '?'
};
return str.replace(/./g, char => {
const lowerChar = char.toLowerCase();
return map[lowerChar] || lowerChar;
});
};
// Test cases
console.log("PLAYING ?", convertLang("PLAYING"));
console.log("BETA ?", convertLang("BETA"));
console.log("HELLO ?", convertLang("HELLO"));
console.log("PYTHON ?", convertLang("PYTHON"));
PLAYING ? ?l????g BETA ? ???? HELLO ? h?llo PYTHON ? ???h??
Conclusion
This solution efficiently converts English letters to Greek equivalents using object mapping and regular expressions. Characters without Greek mappings are converted to lowercase and preserved in the output.
