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 *

This website stores some user agent data. These data are used to provide a more personalized experience and to track your whereabouts around our website in compliance with the European General Data Protection Regulation. If you decide to opt-out of any future tracking, a cookie will be set up in your browser to remember this choice for one year. I Agree, Deny
504