Leveraging JavaScript for morsecode encryption

I'm in the process of creating a program to convert any text string to Morse Code in a straightforward manner. As a beginner in programming, I'd appreciate any advice on methods I could utilize.

At the moment, I've defined a phrase (string) and an array containing the Morse Code equivalents, but I'm struggling with the next steps of extracting each character from the string, comparing it with the array, and outputting the Morse Code representation of the string.

var sentence = "sink or swim";

var morse = [".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."];

for(i=0; i<sentence.length; i++){

char = sentence.charAt(i);

WScript.echo(char + " | " + i);
}  

Answer №1

If you're looking for a way to encode text into Morse code, you can create a dictionary like the one below:

var morseCodeAlphabet = {
    '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': '-----', 
}

"This is a sentence containing numbers: 1 2 3 4 5"
    .split('')            // Convert the string into an array
    .map(function(char){  // Replace each character with its Morse code equivalent
        return morseCodeAlphabet[char.toLowerCase()] || ''; // Use lowercase and ignore unknown characters
    })
    .join(' ')            // Convert the array back to a string
    .replace(/ +/g, ' '); // Remove any double spaces that may have occurred

// Morse code output: "- .... .. ... / .. ... / .- / ... . -. - . -. -.-. . / -.-. --- -. - .- .. -. .. -. --. / -. ..- -- -... . .-. ... / .---- / ..--- / ...-- / ....- / ....."

Answer №2

To begin with, the first step is to remove any characters that cannot be encoded:

phrase = phrase.toLowerCase().replace(/[^a-z]/g, "");

By utilizing the replace function along with a regular expression, the outcome will be a string containing only alphabetic characters. Additionally, all letters are converted to lowercase for simplicity.

Subsequently, within the for loop:

c = phrase.charCodeAt(i);

This action transforms the letter into its corresponding ASCII code value. The resulting morse code would then be morseCode[c - 97].

While Gerald Schneider proposes enhancing this encoding technique by incorporating numbers, it would introduce a level of complexity to the code.

Answer №3

To achieve a one to one mapping, consider converting the array to an object. This approach ensures that unwanted characters do not interfere with the output as the decode function will filter them out if they are not found as a key.

var morseObj = {};
for (var i = 97, l = 97 + morseCode.length; i < l; i++) {
  morseObj[String.fromCharCode(i)] = morseCode[i - 97];
}

Subsequently, create a decode function as follows:

function encode(sentence) {
  var output = '';
  for (var i = 0, l = sentence.length; i < l; i++) {
    var letter = sentence[i].toLowerCase();
    if (morseObj[letter]) { output += morseObj[letter] + ' '; }
  }
  return output;
}

encode('My name is Andy'); // "-- -.-- -. .- -- . .. ... .- -. -.. -.-- "

Check out the DEMO

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

HTML - implementing a login system without the use of PHP

While I am aware that the answer may lean towards being negative, I am currently in the process of developing a series of web pages for an IST assignment in Year 9. Unfortunately, the web page cannot be hosted and our assessor lacks the expertise to utiliz ...

Displaying an alert message when incorrect login credentials are detected in React Native

My objective is to display an alert message when a user login attempt fails, however, the alert does not appear. Below is the code I am using in React Native: login onPressLogin(){ fetch('http://192.168.1.10:3000/users/login',{ m ...

Creating Dynamic Lists with React Native

<Search ref="search_box" onSearch={this.onSearch} backgroundColor="white" cancelButtonTextStyle={{ color: "red" }} placeholder="Search Food..." ...

Having trouble with the "setValue" property being undefined error. Looking for a solution to input text into a codeMirror element using Selenium WebDriver with Java

Currently, I am attempting to input text into a textarea field that is recognized as CodeMirror. Below is the code snippet I have been working with: {... WebElement scriptField = this.getDriver().findElement(By.cssSelector(".CodeMirror-line>span")); ...

Leveraging Selenium to extract text from a dynamically populated DIV using JavaScript

I am currently utilizing Selenium to automatically retrieve all comments from a New York Times article. Once the comments are loaded, my goal is to extract them and save the information for future use. However, upon inspecting the source code of the articl ...

Is it possible to integrate the Firestore npm library into my Express application?

Recently, I created my own library to act as a nosql database on my node.js web server in place of mongodb. I came across this interesting quote: Applications that use Google's Server SDKs should not be used in end-user environments, such as on pho ...

When attempting to display an updated value in a dialog window using an ajax response for the second time, the change

Upon submission of my form, a PHP script is triggered via AJAX to perform validation. Currently, the script simply echoes the post value. For example, if a user inputs "Dog" into "formEntry," the AJAX response will display Dog. However, if the user cancels ...

Encountering an undefined response in API call using Fetch with Express Nuxt

I've hit a roadblock with a task involving Express, API, and Fetch. I'm utilizing Nuxt along with Shopify API endpoints to retrieve data such as orders. Below is my express API Endpoint which should return an array of objects (orders). const bod ...

Loading content synchronously

Could you assist me in finding a solution to synchronize the loading of pages and elements? Currently, my code looks like this: $(Element).load(File); ... other commands... window.onload = function () { Update_Elements(Class, Content); } Everything ...

Creating a personalized scrollbar for the body using Bootstrap 3

I've been searching for the best solution to customize the scroll-bar in Bootstrap, but I haven't found anything that works perfectly yet. I want to replace the default browser scroll-bar on the body and other elements like panels, wells, and tex ...

In React, the state's value will revert back to its initialState whenever a new value is assigned

My App component has a simple functionality where it controls the state of a value to display a header. By using an onClick function, I'm updating the isHeaderVisible value to True in the Home component when a logo is clicked and another route is take ...

The issue with Angular 2's Parameterised router link component not fully refreshing

I'm trying to figure out how to show a set of images when I click on a specific menu item. The menu structure looks like this: <ul id="demo23" class="collapse"> <li> <a [routerLink]="['image-gallery','Picasso ...

Include a quantity dropdown menu on the cart page of your Shopify store's debut theme

Hey there! I'm currently customizing the Shopify Debut theme and I'm trying to incorporate a quantity selector as a dropdown on the cart page. Unfortunately, I'm encountering some issues with this implementation. I've managed to succes ...

It appears that Nodemon has stopped functioning correctly. To use Nodemon, simply input the following command: nodemon [nodemon options]

nodemon has always been reliable for me. I used to run nodemon server and it would automatically watch for updates and restart the server file. However, lately when I try to do this on my Windows cmd, I get the following message: Usage: nodemon [nodemon o ...

Switch out a specific string within a JavaScript object

{ 1:' {person} experimenting for 1 ', 2:'{person} experimenting for 2 ', 3:'{person} experimenting for 3 ', 4:'{person} experimenting for 4 ', 5:'{person} experimenting for 5 ' } Imag ...

Identifying Errors in Meteor's Data Publications

I am currently working on a web application using Meteor and AngularJS 2. Take a look at the publication function below: Meteor.publish('abc', function () { // For throwing the meteor error according to the condition if(!this.userId) throw new ...

Picking out specific elements from a component that is rendered multiple times in a React application

One of the challenges I face involves a component called card, which is rendered multiple times with different data. Here's how it looks: { this.state.response.reminders.map((item,i=0) =>{ return <Card key={i++} reminder={item} deleteRem={th ...

Is it possible to assign the margin-bottom property of one element to be equal to the dynamic height of a sibling element?

I am in the process of creating a website that features a fixed (non-sticky) footer placed behind the main content using the z-index property. The footer only becomes visible when the user scrolls to the bottom of the page, achieved by assigning a margin-b ...

Can we add to the input field that is currently in focus?

Recently, I've been working on a bookmarklet project. My goal is to append an element to the currently focused input field. For instance, if a user clicks on a textarea and then activates my bookmarklet, I want to insert the text "Hello" into that sp ...

Is there a way to personalize the chart tooltip in jqplot to fit my preferences?

I have a chart that displays data. I would like the x-axis labels to show in the format MM/DD, and in the tooltip, I want to display data in the format HH:y-axis. For example, in the chart below, I want the x-axis labels to be 'Oct 15','Oct ...