After seeing Google's april fools joke of the morse code gmail, I thought I'd try to create a real-time morse code converter in javascript.
I'm using regex and replace to change the morse code into character. For example:
.replace(/.- /g, "a").replace(/.-. /g, "r")
The issue I'm having is that when I'm typing .-.
for "r" it give me an "a" because it sees .-
first.
How can I make it replace only exact matches?
Updated and working!! Thanks to every one that helped me
http://jsfiddle.net/EnigmaMaster/sPDHL/32/ - My Original code
http://jsfiddle.net/EnigmaMaster/LDKKE/6/ - Rewritten by Shawn Chin
http://jsfiddle.net/EnigmaMaster/y9A4Y/2/ - Rewritten by Matthias Tylkowski
If anyone has other ways of writting this program please post a JsFiddle
Id love to see how else this can be done
Your question highlights an interesting fact: the Morse code is not a prefix code. So you need some kind of separator—spaces, commas, etc.—to delimit code symbols.
You seem to have decided to use spaces, that's fine.
This being said, what's missing in your regex is the escaping of the dot symbols (use /\.- /
instead of /.- /
)
Another way of doing it is using a dichotomic search.
A graphical representation of the dichotomic search table: the user branches left at every dot and right at every dash until the character is finished.
The other answers have already covered the reasons why your example was not working so I'll refrain from repeating them.
However, may I suggest that since you're already using spaces to delimit each code, a straight-forward solution would be to do a simple .split()
to segment the input text into individual units then simply do a one-to-one mapping of code to chars.
This will be a lot more efficient than repeated regex replacements and less prone to errors.
For example:
var morse = { // use object as a map
'.-': 'a',
'-...': 'b',
'-.-.': 'c',
// .... the rest ...
};
function translate_morse(code) { // given code, return matching char
return (typeof morse[code] === "undefined") ? "" : morse[code];
// if the var is not found, the code is unknown/invalid. Here we
// simply ignore it but you could print out the code verbatim and use
// different font styles to indicate an erroneous code
}
// example usage
translated = code_text.split(" ").map(translate_morse).join("");
Here's a working example: http://jsfiddle.net/KGVAm/1/
p.s. I've taken the liberty of tweaking the code and the behaviour a little, i.e. disabling the input of other chars but allowing backscape to allow corrections.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With