Leveraging Regular Expressions for Matching Array Elements in Switch Cases

I'm currently developing a fun 'hangman' game for my wife's history course. As part of this project, I've constructed a class that generates the 'gameWord' in both string and array formats.

As an additional feature within this class, I aim to create another array that is visible to the player and changes based on their input. This array should display a '*' for each letter and a '_' for each space.

I've experimented with using regex in if or switch statements while looping through the gameWord array but haven't had much success so far. Here's one of my initial attempts:

class GameWord {
  constructor(word) {
    if ( word.length <= 3 )
      return console.error('Error: Your word must be at least three letters long');

      this.word = word.replace(/[^a-zA-Z\s]/g, ''); 
      this.wordUserView = this.word.toProperCase( );
      this.wordSet = this.wordUserView.split('');

    const len = this.wordSet.length;
    var i = 0;

    this.wordSetHidden = [];
    for ( ; i <= len; i++) {
      if (this.wordSet[i] == /[a-zA-Z]/g) {
    this.wordSetHidden.push("*");
      }
    };
  }
};

And here's another example of something I've attempted:

var reAlpha = /[a-zA-Z]/;
var reSpace = /\s/;
var arr = ["W", "i", "n", "s", "t", "o", "n", " ", "1", 2, 0];
var newArr = [];

for ( var i = 0; i < arr.length; i++ ) {
  switch (arr) {
    case reAlpha.match:
      newArr.push(arr[i] = "*");
    case reSpace.match:
      newArr.push(arr[i] = "_");
    break;
  default: console.log("No matches")
  };
}

When working on these solutions, I keep encountering the "No matches" result because direct comparisons are not being made to the elements in the array. However, trying something like element.match(arr) results in an error stating that match isn't a function, likely because it's interpreting the element as an object rather than a string?

While I'm aware that CSS can be used to hide individual letters, I prefer having the game logic handled on the backend to prevent students from easily viewing the answers by modifying the CSS.

Thank you!

Answer №1

To obscure a word as a string, you can utilize the replace function along with regex to substitute characters with '*' and spaces with '_':

var secretWord = "Confidential123";
var hiddenWord = secretWord.replace(/[^\s]/g, '*').replace(/[\s]/g,'_');

If the word is in an array format, you can incorporate an if statement within your loop:

var letters = ["C", "o", "n", "f", "i", "d", "e", "n", "t", "i", "a", "l", "1", "2", "3"];
var disguisedLetters = [];

for ( var j = 0; j < letters.length; j++ ) {
  if(/[^\s]/.test(letters[j])){
    disguisedLetters.push(letters[j] = "*");
  } else {
    disguisedLetters.push(letters[j] = "_");
  }
}

Answer №2

In this scenario, utilizing an if statement is recommended.

Should you opt to go with a switch

var reAlpha = /[a-zA-Z]/;
var reSpace = /\s/;
var arr = ["W", "i", "n", "s", "t", "o", "n", " ", "1", 2, 0];
var newArr = [];

for ( var i = 0; i < arr.length; i++ ) {
  switch (true) {
    case reAlpha.test(arr[i]):
      newArr.push(arr[i] = "*");
    case reSpace.test(arr[i]):
      newArr.push(arr[i] = "_");
    break;
      default: console.log("No matches");
  };
}

If

var reAlpha = /[a-zA-Z]/;
var reSpace = /\s/;
var arr = ["W", "i", "n", "s", "t", "o", "n", " ", "1", 2, 0];
var newArr = [];

for ( var i = 0; i < arr.length; i++ ) {
  if (reAlpha.test(arr[i]) {
    newArr.push(arr[i] = "*");
  } else if (reSpace.test(arr[i])) {
    newArr.push(arr[i] = "_");
  } else {
    console.log("No matches");
  }
}

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

What is the relationship between $.when, apply(), and $.done() within the scope of this function?

I recently received this function from a helpful SO user that allows for returning a variable number of jQuery $.get() requests. The initial part seems pretty straightforward, but I am struggling to understand how $.when(), apply(), and $.done() are inte ...

The reflight response received an unexpected HTTP status code of 500

Recently, I've been working on utilizing the Yelp Fusion API by making a simple ajax call. I started off by using the client_id and client_secret provided by Yelp to successfully obtain an access token through a 'POST' request in Postman, fo ...

Manage form submission seamlessly without redirecting. Capture information without needing to prevent the default action, then proceed with redirection. Avoid redirecting when using preventDefault, but be aware that data may not

Currently stuck in a tricky situation. I've implemented a custom form submission to prevent redirecting when an express route is triggered by form submission. However, the issue arises when I lose the data being sent without redirection. document.get ...

Enhance records within an array with multiple nested levels of documentation

I have a JSON structure stored in my MongoDb database and I need to update a specific value within a nested array. Specifically, I want to change the key targetAreaId from USER_MESSAGE to VISUAL_MESSAGE. { "_id" : "5cde9f482f2d5b924f492da2", "scenario" : ...

Combining several files into a single variable to encode

I'm encountering an issue with the multiple file upload option. Even though it shows that 2 files have been uploaded, when I try to print the encoded value in the console, it only encodes and takes the value of my last uploaded file. How can I encode ...

Error: The index "id" is not defined

Hey there, I have been working on fetching data from a JSON URL located at this link. However, I seem to be encountering an error that I can't quite comprehend. If anyone has any insights or solutions, I would greatly appreciate the help. Thank you in ...

Enhance ant design modal functionality by enabling resizing capabilities

I'm experiencing an issue with the Ant Design Modal component as it does not support resizing the modal window. I'm looking for a way to enable manual resizing of the modal window once it has been opened. Is there a solution available for this fu ...

Unable to retrieve req.body data, despite having body-parser enabled

I've been working on setting up my login functionality, but I'm running into an issue with accessing the req.body object. Initially, the post route wasn't triggering at all (no console.log output in terminal) and the request would eventuall ...

Searching and replacing query strings in a URL using JQuery according to the chosen option in an HTML dropdown menu

Is there a way to use jQuery to dynamically change a specific value in the query string by finding and replacing that value based on the selection made from a dropdown menu on the webpage? For example: Imagine we have this query string on the current page ...

What is the best way to perform calculations within a PHP loop for <input> elements and then display the results using a JavaScript loop?

Hello everyone, I'm currently struggling with displaying the calculations from a loop of input tags. What I'm trying to achieve is having 5 rows with input fields. At the end of each row, there should be a span area that displays the calculation ...

Error: The request to /api/auth/login in Postman failed unexpectedly

As I am working on developing an app using node.js and express, I encountered an error while making post requests in Postman. Cannot POST /api/auth/login%0A Below are the details of my app's structure along with the files involved: app.js const ex ...

What is the best way to iterate through an array containing multiple objects in order to create a graph?

My API response contains multiple objects organized in an array: [{"symbol":"AAPL","date":"2020-02-27","adj_close":68.24}, {"symbol":"TSLA","date":"2020-02-27","adj_close":133.8}, {"symbol":"TSLA","date":"2020-02-28","adj_close":122.3}, {"symbol":"AAPL" ...

The Angular Sortable Containment feature ensures that items cannot be dropped outside of

I am experiencing an issue with a horizontal sortable Angular list where the containment option is not functioning properly, causing the dragged item to not be dropped. Take a look at the sortable list below without a containment option - you may notice t ...

Ensuring the dropdown menu's functionality in AngularJS

I'm currently working on a code snippet that validates when the user moves away from a specific select element. The goal is to change the border color of the select element to either red or green only when the user tabs away from it or moves the mouse ...

Having trouble choosing the component-button using Protractor

I'm having trouble selecting the "Add New" button using any locator component. Check out the audience.po.ts file and the method "ClickAddNewBtn()": clickAddNewBtn() { console.log("Clicking on the Add New button."); return element(by.cs ...

Why am I seeing numbers in the output when I log the data from the res.write(data) function in Node.js?

While working with Node.js on my Raspberry Pi, I encountered an issue where reading a local file 'test.html' resulted in hex output instead of the expected HTML format. Can someone explain why this might be happening? Additionally, I am aware tha ...

The JavaScript counterpart to jQuery's click event handler

I'm trying to figure out how to achieve the same effect as this jQuery code. var divQuery = $('.html5gallery-thumbs-0').children(); divQuery.on('click', function () {...} I attempted it like this: var divQuery = document.g ...

Guide on viewing chromedriver logs during Protractor testing

I've recently discovered that chromedriver has the ability to generate a logfile (https://sites.google.com/a/chromium.org/chromedriver/logging) While the process of setting up this feature when running the executable directly is clear: chromedriver. ...

What is the reason for having getDerivedStateFromProps as a static method?

Currently, I haven't started working on the static getDerivedStateFromProps method, so I am looking to gain more insight about it. I am aware that React has deprecated componentWillReceiveProps in React v16+ and introduced a new lifecycle method call ...

Regular expression that identifies the line ending with a specific word, not just a similar one

When attempting to parse a configuration file and display the results on a web interface, I encountered an issue with my regular expressions producing extra output. Here is an example of the code snippet causing the problem: lbvs = lb-vs-pr-443-v1-abhishe ...