I have created an English to Morse Code translator that requires a space between each Morse Code letter. In order to do this I added an extra space after every letter in the dictionary that can be seen below. However, this means at the end of the sentence there is an extra space (" "). Is there any way to remove this space?
I have attempted to use the str.slice function and it removes the whole morse code version of the last letter.
function morseCode(str) {
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": "--.. ",
'1':'.---- ',
'2':'..--- ',
'3':'...-- ',
'4':'....- ',
'5':'..... ',
'6':'-.... ',
'7':'--... ',
'8':'---.. ',
'9':'----. ',}
str = str.replace(/[!,?]/g , '');
str = str.replace(/\s/g, '');
return str.toUpperCase().split("").map(el => {
return morseCode[el] ? morseCode[el] : el;
}).join("");
};
Since the str.slice function returns the sliced part between two index as a substring, in your case, you should use str.slice(0,-1)
, that is equals to str.slice(0, str.length - 1)
. And it means that is going to return every character from zero index without the last character of the string passed.
function morseCode(str) {
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": "--.. ",
'1':'.---- ',
'2':'..--- ',
'3':'...-- ',
'4':'....- ',
'5':'..... ',
'6':'-.... ',
'7':'--... ',
'8':'---.. ',
'9':'----. ',}
str = str.replace(/[!,?]/g , '');
str = str.replace(/\s/g, '');
return str.toUpperCase().split("").map(el => {
return morseCode[el] ? morseCode[el] : el;
}).join("").slice(0,-1); // this returns the string without the last character.
};