Design a function that accepts a string parameter and outputs an encoded (h4ck3r 5p34k) rendition of the input string

 function convertToHacker(str){
    for (var i=0; i <str.length;i++)
      {
    if (str[i]==="a")
       {str=str.replace("a","4")}
    else if (str[i]==="e")
        {str=str.replace("e","3")}
    else if (str[i]==="i") 

     {str=str.replace("i","1")}
    else if (str[i]==="o")
          {str=str.replace("o","0")}
    else if (str[i]==="s")
          {str=str.replace("s","5")}
    else {}
        }
    return str
  }

  document.write (convertToHacker("become a coder"))

The output is not as expected and upon checking the code, it seems there are issues with comparison operators ('=' instead of '=='). The function should replace all 'a's with 4, 'e's with 3, 'i's with 1, 'o's with 0, and 's's with 5.

Answer №1

String#replace function does not alter the original string (it is non-mutating), rather it creates and returns a new one.

My recommendation would be to continue using the replace function but also experiment with regular expressions :)

const dictionary = {
   a: 4,
   e: 3,
   i: 1,
   o: 0,
   s: 5,
};

function hackerSpeak(str) {
  return str.replace(/[aeios]/gi, (m) => dictionary[m]); 
  // this will produce a modified version of the string
}

document.write(hackerSpeak("become a coder"))

Answer №2

function convertToHackerSpeak(statement) {
    const leet = {'a': 4, 'b': 3, 'i': 1, 'o': 0, 's': 5}
    const speak = letter => leet.hasOwnProperty(letter) ? leet[letter] : letter

    return statement.split('').map(speak).join('')
}

console.log(convertToHackerSpeak("I am learning to code like a pro"));

Answer №3

Let's clarify something: In JavaScript, a single "=" is not a comparison operator; it is used for value assignment. To compare two values, use "==" or "===".

For string comparison, it is recommended to use the ".equals(...)" method.

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

Is there an issue with .addClass not working on imported HTML from .load in jQuery?

I have set up a navigation bar that hides when the user scrolls down and reappears when they scroll up. I want to keep the navbar code in a separate HTML file for easier editing. .load In the index.html file, the navbar code is included like this: <di ...

Function activation in Element requires a double click to initiate

I've encountered an issue with a web element I'm working on where the click function only triggers after the first click, rendering the initial click ineffective. Here's the code snippet in question: HTML: <div> <a href="#0" cla ...

Customize Google Chrome to display a vibrant splash screen instead of a boring white blank page when

"I've been on the lookout for Chrome apps that can help make my screen darker or inverted to reduce eye strain. While I have found some apps that do the job, there's one thing they don't seem to be able to override - the White Blank page. W ...

Avian-themed masking feature for jCarousel

Currently, I have a series of images in constant motion using jCarousel. Only one image is visible fully at any given time, and I am looking to create a "feathering" effect on the edges of the carousel so that the images smoothly fade in and out as they co ...

Adding a JavaScript object into the $http service

Struggling to correctly insert an object in this format: $scope.newObj = {1: "N/A", 2: "KO", 3: "OK", 4: "OK", 5: "OK", 15: "N/A", 19: "OK"} An attempt was made using the following loop: var objt = $scope.newObject; console.log($scope.newObject[0] ...

Grabbing an element with Cheerio in Node.JS

Struggling to extract the price element from this page: Running the console.log returns nothing, even though I'm certain I'm targeting the correct element. Any advice on how to tackle this issue? var request = require('request'); var ...

Utilizing class attributes within multiple classes

I have created a custom class called MutationValidator as follows: const ERR_MSG = 'Error1'; @Service() export class MutationValidator { .. } This class is used in another class like so: import { MutationValidator } from './mutation ...

Acquire the id_token from Google using oauth2

I am currently working with AngularJS on the client side and trying to implement Google OAuth2. While I have successfully obtained the access token, I now need to retrieve the ID token. In order to achieve this, I have made modifications in app.js, contro ...

What is the best way to run tests on this asynchronous function using Jasmine?

My role in the service is listo: function () { var promiseResolved = $q.defer(); setTimeout(function () { promiseResolved.resolve(true); }, 2000); return promiseResolved.promise; } During my testing ...

Utilize moment.js to format a datetime and display the corresponding timezone

I'm having trouble displaying timezones correctly using moment.js. I attempted to use the following code: var result = moment(someDate).format("MM/DD/YYYY HH:mm A Z"); This returns something like: 08/05/2015 06:18 PM +02:00, which is okay, but I w ...

Troubleshooting the ckeditor-duplicated-modules error when trying to install a local npm package that should utilize the node_modules of the main project through yarn

As I work on my MainProject, I'm attempting to set up a local version of the ckeditor-5 plugin PeteCkPlugin that was generated using the ckeditor5 package generator. I experimented with using yarn link within the local directory of PeteCkPlugin, foll ...

Presenting a 24-column data table fetched from MySQL and integrated into a webpage through JavaScript DataTables

Greetings everyone! I have a query regarding Javascript DataTables and how it displays data from a MySQL table. Here's the MySQL query in question: select LOT_LOCATION, `Zone Attribute`, a.LOTID, Design_ID, ifnul(Board_ID,'') as Board_ID1, ...

The selection button's threshold

Welcome to my website design project! I have implemented image buttons for my web page and want to restrict the number of images a user can select. If a user tries to navigate away after selecting more than 3 images, I wish to display an alert message. Her ...

Having trouble with Vuex actions. Getting an error message that says "Failed to signInWithEmailAndPassword: The first argument "email" must be a valid string."

I recently started exploring Vuejs state management. I attempted to create a login system with Firebase using Vuex. However, I encountered the following error: signInWithEmailAndPassword failed: First argument "email" must be a valid string I'm havi ...

Tips for merging two JSON files to create a single associative array

How can I merge two similar JSON files in JavaScript, where elements from each are combined into a new associative array in a specific pattern? For example: var JSON1 = {'Item 1':123, 'Item 2':234, 'Item 3': 345} var JSON2 = ...

Next.js 13 React Server Component not displaying updated data upon build completion

I have a React Server Component that retrieves its data at build time and does not reload it while the site is running. I expected it to fetch the data once when the server component is first rendered. Is there a way to force this server component to relo ...

Tips on revitalizing a bootstrap wizard

In my JSP file, I am using a Bootstrap wizard. You can see the wizard layout in the following link: The wizard allows me to add employee elements that are stored in a JavaScript array (I also use AngularJS). At the final step of the wizard, there is a su ...

Discover identical HTML elements

I have a simple HTML code that I would like to split into similar parts: <input id="checkbox1"><label><br> <input id="checkbox2"><label><br> <input id="checkbox3"><label><br> The desired result should ...

Displaying outcomes solely based on JSON upon choosing a filter

Goal I aim to only show results once their respective state is chosen. Currently, all results are displayed automatically upon page load. I prefer if nothing is shown initially. Only when a state is selected should the corresponding results appear. Bac ...

Traveling within a layered object

Currently, I'm working with an object and iterating through it to retrieve outputs as shown below: var obj = { "first": { "Bob": { "1": "foo", "2": "bar" }, "Jim": { "1": "baz" } }, "second": { "Bob": { ...