Morse code is almost 200 years old, and it is still everywhere: ham radio, aviation, emergency signals, even accessibility switches. I recently built a free online translator, and the core of it turned out to be surprisingly small — a lookup table and two functions. Here is the whole thing, open-sourced.
The map
International Morse (ITU) assigns every letter, digit and common punctuation mark a pattern of dots and dashes:
const MORSE_MAP = {
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: "--..",
1: ".----", 2: "..---", 3: "...--", 4: "....-", 5: ".....",
6: "-....", 7: "--...", 8: "---..", 9: "----.", 0: "-----",
".": ".-.-.-", ",": "--..--", "?": "..--..", "!": "-.-.--", "@": ".--.-."
// ...full punctuation set in the repo
};
Encoding: text → Morse
Split the text into words, map each character, join letters with a space and words with /:
function textToMorse(text) {
return text.toUpperCase().split(" ")
.map(word => [...word].map(ch => MORSE_MAP[ch] || "").filter(Boolean).join(" "))
.filter(Boolean).join(" / ");
}
textToMorse("HELLO WORLD");
// ".... . .-.. .-.. --- / .-- --- .-. .-.. -.."
Decoding: Morse → text
Reverse the map once, then walk the code word by word:
const REVERSE_MAP = Object.fromEntries(
Object.entries(MORSE_MAP).map(([ch, code]) => [code, ch])
);
function morseToText(morse) {
return morse.trim().split(/\s*\/\s*|\s{3,}/)
.map(word => word.split(/\s+/).map(code => REVERSE_MAP[code] || "").join(""))
.join(" ").trim();
}
morseToText("... --- ..."); // "SOS"
That is genuinely all you need for text. The full source (with the complete punctuation map) is on GitHub: https://github.com/abdulbari-34/morse-code-translatorr — MIT licensed, zero dependencies, works in Node and the browser. There is also a live demo of the library in action in the repo's GitHub Pages site.
Where it gets harder
Text is the easy part. The interesting problems start when Morse arrives as sound: detecting beeps in a noisy recording, guessing the sender's speed (WPM) and Farnsworth spacing, and cleaning up sloppy hand-sent code. That is the part I ended up building into the full Morse Code Translator, which also decodes Morse from audio files, images and video — the Morse Code Audio Decoder page explains how the audio side works.
If you do anything with the library — a trainer, a game, a blinkenlight — I would love to see it in the comments.
Top comments (0)