Tips for converting characters in an array to a Caesar cipher

I tried setting up an array that correlates capital letters with their corresponding Caesar cipher letters, so for example, A would shift 13 places to become N. I attempted to write a code that could generate this transformation, but I seem to have made an error. Can someone assist me in identifying where I went wrong and explain the mistake briefly?

let abcToCesar = [
  {abc: "A", cesar: "N"},
  {abc: "B", cesar: "O"},
  {abc: "C", cesar: "P"},
  {abc: "D", cesar: "Q"},
  {abc: "E", cesar: "R"},
  {abc: "F", cesar: "S"},
  {abc: "G", cesar: "T"},
  {abc: "H", cesar: "U"},
  {abc: "I", cesar: "V"},
  {abc: "J", cesar: "W"},
  {abc: "K", cesar: "X"},
  {abc: "L", cesar: "Y"},
  {abc: "M", cesar: "Z"},
  {abc: "N", cesar: "A"},
  {abc: "O", cesar: "B"},
  {abc: "P", cesar: "C"},
  {abc: "Q", cesar: "D"},
  {abc: "R", cesar: "E"},
  {abc: "S", cesar: "F"},
  {abc: "T", cesar: "G"},
  {abc: "U", cesar: "H"},
  {abc: "V", cesar: "I"},
  {abc: "W", cesar: "J"},
  {abc: "X", cesar: "K"},
  {abc: "Y", cesar: "L"},
  {abc: "Z", cesar: "M"},
]

function toCaesar(str) {
  for(let i = 0; i < str.length-1; i++){
      for(let i = 0; i < abcToCesar.length; i++){
          if(str.charAt(i) == abcToCesar[i].abc){
              str.charAt(i) == abcToCesar[i].cesar
          }
          else{
              return str.charAt(i)
          }
      }
  }
  return str;
}

console.log(toCaesar("SERR PBQR PNZC"));

Answer №1

JavaScript has immutable strings, making it impossible to assign a new character to a specific index. Instead of using == for assignment, consider constructing a new string by iterating over the original one. One way to handle uppercase letters is by utilizing String#replace.

It is not necessary to list every letter individually. Uppercase ASCII letters have consecutive values, allowing you to simply add 13 to the character code and then convert it back to a string.

function toCaesar(str) {
  const A = 'A'.charCodeAt();
  return str.replace(/[A-Z]/g, c => String.fromCharCode(A + (c.charCodeAt() - A + 13) % 26));
}

console.log(toCaesar("SERR PBQR PNZC"));

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

Utilize pivot to manage user roles and permissions in ExpressJS application using Mongoose

My user schema is structured as shown below const userSchema = mongoose.Schema({ username: { type: String, required: true, }, first_name: { type: String, required: true, }, last_name: { type: Stri ...

Importing .js files from the static folder in Nuxt.js: a step-by-step guide

I'm in the process of transitioning my website, which is currently built using html/css/js, to Nuxt.js so that I can automatically update it from an API. To maintain the same website structure, I have broken down my code into components and imported ...

What is the best way to integrate the express-session logic with Prisma for optimal performance?

Hi there, I recently started using Prisma and want to integrate it with PostgreSQL. My main goal is to implement authentication in my backend, but I encountered issues while trying to create a session table. When working with raw SQL, I managed to add the ...

Issue with variable creation within ng-repeat

After reading a question on StackOverflow about determining the number of filtered out elements, I wrote the following code in Angular: <input type="text" ng-model="query" placeholder="Enter query..."> <div ng-if="filteredData.length!=data.length ...

Issues with zoom functionality not functioning properly within IE11

I am currently developing an application with Angular that is designed to be compatible with tablets and touch-enabled devices. One of the key features I want to implement is the ability for users to zoom/scale up the app, especially for those with visual ...

Other elements are unable to conceal Material UI InputBase

Displayed below is a navigation bar that sticks to the top, followed by rows of InputBase components from material-ui. Despite setting the background color of the nav bar to white, the input always appears above the nav. This strange behavior stopped when ...

Add items to a separate array only if the material UI checkbox is selected

Exploring the world of React, I decided to create a simple todo app using React JS and Material UI. With separate components for user input (TodoInput.js) and rendering individual todos with checkboxes (TodoCards.js), I aim to display the total number of c ...

Utilizing highlight.js for seamless integration with vue2-editor (Quill)

I am having trouble connecting vue2-editor (based on quill) with highlight.js Despite my efforts, I keep encountering an error message that reads: Syntax module requires highlight.js. Please include the library on the page before Quill. I am using nu ...

Guide to utilizing JSDoc within your local project

Objective My goal is to utilize jsdocs with npm in my project. Experience I am new to working with npm and its plugins. Recently, I came across jsdoc and attempted to incorporate it into my project without success. Attempted Solution Initially, I inst ...

Utilizing a .ini file to assign variables to styles elements in Material-UI: A comprehensive guide

I need to dynamically set the background color of my app using a variable retrieved from a .ini file. I'm struggling with how to achieve this task. I am able to fetch the color in the login page from the .ini file, but I'm unsure of how to apply ...

Determine if a Node.js Express promise holds any data

I'm looking for assistance with my nodejs application that returns a promise. What I need help with is figuring out how to determine if the result of this promise contains data or if it's just an empty array. I attempted using Object.keys(result) ...

Shining a component (or persona) however essentially duplicate a distinct term

Is it possible to highlight an element or word, but still copy a different word when hitting ctrl+c? For example, imagine I have an emoji represented by: Original text: :heart: Output in HTML: <span background={...logic here}></span> I am ...

Ways to conceal various components while showcasing just a single element from every individual container

I am looking to only display specific span elements within their parent container (coin) while hiding the rest. The desired output should show only "1" and "first" while the other spans are hidden. <div class="types"> <div class=" ...

Issue with Titanium: Unable to scroll within tableview

The tableview is not scrolling as expected. I tested it on a mobile device and the scrolling worked fine, but it doesn't seem to work on tablets. Please assist. CODE var win = Titanium.UI.createWindow({ title : 'Medall app', back ...

Is it possible to bind computed values in Ember using .properties(...) with ember-model?

I'm attempting to utilize the .property('key') syntax in order to update a computed value within my model. The structure of my model is as follows: App.Camera = Em.Model.extend({ id: attr(), uid: attr(), name: attr(), type: ...

The issue of a false value not being correctly matched in Jasmine is causing problems

Currently, I am utilizing the following code to evaluate an element with aria-checked="false". expect((accessPolicyPage.listSelectAll).getAttribute("aria-checked")).toEqual("false"); The output is presenting as Expected [ 'false' ] to equal &ap ...

PHP JSON structure - something unusual

Working with the Google Tag Manager API (v2) has presented a challenge as I try to update my existing JSON array. Initially, adding data to my JSON object caused it to appear on the last row instead of inside the object. After making adjustments to my cod ...

Adjusting the display of HTML elements depending on geolocation authorization

I am currently facing an issue with my HTML code where I want to show an element only if the user declines to share their location with the browser. However, my code is not functioning as expected when the user rejects the location request. On the other ha ...

Unable to retrieve file from server

Apologies for the basic question, but I'm feeling a bit lost at the moment. I've been diving into learning JavaScript and decided to set up a page on the 00webhost site to experiment and run tests. Everything was going well until I hit a roadblo ...

There is a SyntaxError due to an unexpected token "o" in the JSON data. It is not a valid JSON format

This code is designed to check an XML file to see if the email or login inputted by a user is already in use, and then provide a JSON response. The AJAX code for this functionality is as follows: $.ajax({ type: 'post', dat ...