Cipher Caesar - symbols and additional characters

I've constructed a Caesar Cipher script down below, however, I wish for the output string to contain spaces and other characters. Despite my attempts with regex, it doesn't seem to rectify the issue or maybe I'm not utilizing it correctly – unsure of which.

Any assistance would be greatly appreciated. Thank you!

function caesarCipher(str, n) {
  let newStr = '';
  let alphabet = 'abcdefghijklmnopqrstuvwxyz'.split('')
  let regex = /[a-z]/

  for (let i = 0; i < str.length; i++) {
    if (str[i].match(regex) === false) {
      newStr += str[i]
      continue;
    }
    let currentIndex = alphabet.indexOf(str[i]);
    let newIndex = currentIndex + n;
    newStr += alphabet[newIndex];
  }
  return newStr
}

console.log(caesarCipher('ebiil tloia!', 3)) //should return hello world! but returns hellocworldc

Answer №1

When using <code>RegExp.test, a boolean value is returned while String.match returns an array. To ensure accurate results, consider the following:

If you encounter this line of code: 
if (str[i].match(regex) === false) {

It is recommended to rewrite it as follows:

If (regex.test(str[i]) === false) {

This revised code will effectively handle any values that are not lowercase letters including spaces, punctuation marks, and so on. To include uppercase letters as well, simply add the i flag at the end of the regex pattern like so: /[a-z]/i

Answer №2

To start, ensure that the shift value passed to the function is 3. Next, considering that there are no spaces in the alphabet, you must include a validation step:

function caesarCipher(str, n) {
  let newStr = '';
  let alphabet = 'abcdefghijklmnopqrstuvwxyz'.split('')
  let regex = /[a-z]/

  for (let i = 0; i < str.length; i++) {
    if (str[i].match(regex) === false) {
      newStr += str[i]
    }
    let currentIndex = alphabet.indexOf(str[i]);
    if (!(currentIndex + 1)) {
      newStr += " ";
    } else {
      let newIndex = currentIndex + n;
      newStr += alphabet[newIndex];
    }
  }
  return newStr
}

console.log(caesarCipher('ebiil tloia!', 3)) //should return hello world! but returns hellocworldc

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

ExpressJS exhibits unique behavior based on whether the API is requested with or without the specified PORT number

I have encountered an issue with my 2 flutter web apps. One of them is functioning flawlessly when I request the URL, but the other one only works when I include the port xxxxx:4000/nexus-vote. However, when I remove the port, I receive a status code of 20 ...

Displaying Photo on Webpage using Bearer Authorization Token in JavaScript

In my JavaScript code, I am currently loading an image using the following method: var img = new Image(); img.onload = function () { .. }; img.src = src; However, I have recently realized that I need to secure the images on my server side with OAuth 2, j ...

The unit test for displaying the modal with the ID 'modalId' returned an undefined value

Being a beginner in both unit testing and angularjs, I encountered an issue while trying to test if my modals are displaying correctly. > TypeError: undefined is not a constructor (evaluating '$('#modalId').modal('show')') ...

Creating a JSON object with an array using MySQL

Just a quick question for you... I'm working with a database that has two tables : Articles (id, content, title, date) Comments (id_article, username, content) I am trying to generate a JSON array structured like this : [ { "id": "5785634a ...

What steps can be taken to diagnose the cause of a failed Jquery AJAX request?

I am attempting to utilize the Yahoo Finance API to retrieve data in CSV format through Javascript. However, my current implementation shown below is not successful. $.ajax({ type: "GET", url: "http://finance.yahoo.com/d/quotes.csv?s=RHT+MSFT&f=sb2b3j ...

Incorporating Stripe into your Next.js 13 application: A step-by-step guide

Struggling to incorporate Stripe into my Next.js 13 app for a pre-built checkout form. So far, all attempts have fallen short. Seeking assistance from anyone who has conquered this integration successfully. Any tips or guidance would be highly valued. Pl ...

The Ajax post function is not functioning as expected

Here is my code: $.ajax({ type: "POST", url: "mailyaz.php", data: { name: "testest" } }); Currently, the code works with a simple message of "testest". However, I am trying to post my javascript variable (var mysubjec ...

Is there a way to conceal a component using Twitter Bootstrap while having the ability to reveal it with the help of

Suppose I generate an HTML element in the following manner, <div id="unique-div" class="concealed">Hello, TB3</div> <div id="unique-div" class="hide-me">Greetings, TB4</div> <div id="u ...

The declaration file for module 'react/jsx-runtime' could not be located

While using material-ui in a react project with a typescript template, everything is functioning well. However, I have encountered an issue where multiple lines of code are showing red lines as the code renders. The error message being displayed is: Coul ...

Enhance a collection by incorporating methods to the result of an angular resource query

After executing a query, I am left with an array from the resource: .factory('Books', function($resource){ var Books = $resource('/authors/:authorId/books'); return Books; }) I was wondering if there is a way to incorporate pr ...

Using nodeJS to showcase content on a web page

I'm relatively new to NodeJS, and I am trying to figure out if there is a way to utilize NodeJS similar to JavaScript. My goal is to retrieve data from a database and display it within a div on my index.html page. When attempting to use querySelector, ...

Redirect to a new page following a toastr notification in an Angular application

Looking for a way to automatically navigate to another page after a toastr notification disappears. showToasterWarning(){ this.notifyService.showWarning("No Data Found for this Date!", ""); } The notifyService is responsible ...

Making an Ajax request by leveraging the power of an image tag

I am facing a challenge with trying to establish communication on my server between port 80 and port 8080 through an ajax request. I understand the implications of CORS and the cross domain request origin policy, as well as the potential solution involving ...

Executing numerous queries in mongoDB

I need to query multiple collections in MongoDB. Here is an example of the data structure: Collection stops { { stop_id : 1, stop_name: 'a'}, { stop_id : 2, stop_name: 'b'}, ... Collection stop_time { { stop_id : 1, trip_i ...

Execute a database query to search for patterns using Regular Expressions within the

As I embark on a new project, I find myself questioning my approach before diving in too deep and realizing it may not be the most efficient path. Within the realm of a large company where we develop unofficial tools for internal use, I am faced with limi ...

Running a child process in the browser using Node.js with the help of browserify

Utilizing browserify to enable node.js functionality in the browser, I am attempting to run a child process in my index.js file: var exec = require('child_process').exec; //Checking the installed node version var ls = exec('node -v', f ...

Is there a Possible Bug with Highcharts Categories?

I am in the process of creating a dynamic sales dashboard that automatically updates a column chart displaying the latest sales figures for a team of agents. Within this project, I have developed a function called updateChart() which carries out the follo ...

The email message generated by sendGrid is kept confidential

When attempting to send emails using Node.js with SendGrid, I am experiencing an issue where the email content is always hidden. Here is my node.js code: const msg = { to: 'example@example.com', from: 'sender@example.com', ...

Encountering issues with Webpack 2 failing to resolve the entry point specified in the

Encountering an issue while trying to compile my application with webpack 2. This is how my app folder structure looks: / | - dist/ | | - src/ | | | | - modules/ | | | | | | - module1.js | | | | - index.js * | | _ webpack.config.js | | ...

Issue with peculiar circumstances regarding the JSON object and generating a chart, can you pinpoint what's amiss?

When sending data (values and dates) from a hard-coded function, everything works fine - the JSON file is populated and the chart is displayed. However, when I send data from the database, the JSON file is populated but the chart does not appear. Here is ...