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
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:
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.