
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Convert 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 −
-........-...-..-. --.--..---..--.-.- .....-.-- -......-..!
Advertisements