Converting string to MORSE code in JavaScript


What is Morse code?

Morse code is a method used in telecommunications to encode text characters as standardized sequences of two different signal durations, called dots and dashes.

To have a function that converts a particular string to Morse code, we will need an object that maps all the characters (English alphabets) to Morse code equivalents. Once we have that we can simply iterate over the string and construct a new string.

Here is the object that maps alphabets to Morse codes −

Morse Code Map

const morseCode = {
   "A": ".-",
   "B": "-...",
   "C": "-.-.",
   "D": "-..",
   "E": ".",
   "F": "..-.",
   "G": "--.",
   "H": "....",
   "I": "..",
   "J": ".---",
   "K": "-.-",
   "L": ".-..",
   "M": "--",
   "N": "-.",
   "O": "---",
   "P": ".--.",
   "Q": "--.-",
   "R": ".-.",
   "S": "...",
   "T": "-",
   "U": "..-",
   "W": ".--",
   "X": "-..-",
   "Y": "-.--",
   "Z": "--.."
}

Now the function that converts string to Morse code will be −

Example

const morseCode = {
   "A": ".-",
   "B": "-...",
   "C": "-.-.",
   "D": "-..",
   "E": ".",
   "F": "..-.",
   "G": "--.",
   "H": "....",
   "I": "..",
   "J": ".---",
   "K": "-.-",
   "L": ".-..",
   "M": "--",
   "N": "-.",
   "O": "---",
   "P": ".--.",
   "Q": "--.-",
   "R": ".-.",
   "S": "...",
   "T": "-",
   "U": "..-",
   "W": ".--",
   "X": "-..-",
   "Y": "-.--",
   "Z": "--.."
}
const convertToMorse = (str) => {
   return str.toUpperCase().split("").map(el => {
      return morseCode[el] ? morseCode[el] : el;
   }).join("");
};
console.log(convertToMorse('Disaster management'));
console.log(convertToMorse('hey there!'));

Output

The output in the console will be −

-........-...-..-. --.--..---..--.-.-
.....-.-- -......-..!

Updated on: 24-Aug-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements