Simple Javascript script to convert string to Morse Code.

// © 2017 TheFlyingKeyboard and released under MIT License
// theflyingkeyboard.net

<html>
<body>
    Enter text you want to convert <input type="text" id="textToConvert">
    <button onclick="convert()">Convert</button>
    <p>Text in Morse Code: </p>
    <p id="newText"></p>

    <script>
        function convert(){
            var letters = [ ' ', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0' ];
            var morseLetters = [ "\xa0\xa0\xa0\xa0", ". ___", "___ . . .", "___ . ___ .", "___ . .", ".", ". . ___ .", "___ ___ .", ". . . .", ". .", ". ___ ___ ___", "___ . ___", ". ___ . .",  "___ ___", "___ .", "___ ___ ___", ". ___ ___ .", "___ ___ . ___", ". ___ .", ". . .", "_", ". . ___", ". . . ___", ". ___ ___", "___ . . ___", "___ . ___ ___", "___ ___ . .", ". ___ ___ ___ ___", ". . ___ ___ ___", ". . . ___ ___", ". . . . ___", ". . . . .", "___ . . . .", "___ ___ . . .", "___ ___ ___ . .", "___ ___ ___ ___ .", "___ ___ ___ ___ ___" ];
            
            var textToChange = document.getElementById("textToConvert").value;
            var newText = "";

            for (var i = 0; i < textToChange.length; i++) {
                for (var j = 0; j < 37; j++) {
                    if (textToChange[i].toLowerCase() == letters[j]) {
                        newText += morseLetters[j];
                        newText += "\xa0\xa0\xa0";

                        break;
                    }		
                }
            }

        document.getElementById("newText").innerHTML = newText;
        }
    </script>
</body>
</html>

 

Javascript String To Morse Code
Tagged on:     

Leave a Reply

Your email address will not be published. Required fields are marked *

By continuing to use the site, you agree to the use of cookies. You can read more about it the Cookies&Privacy Policy Section Above. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this. You can read more about it the Cookies&Privacy Policy Section.

Close