Struggling with regular expressions in JavaScript

Creating a senior memory book for my English class is one of my current projects, and being the nerdy student that I am, I've decided to incorporate some code into it. However, I'm facing some challenges with regex in my code. Here's the code snippet I'm working on:

//For future reference, "alert(*parametes*)" will make an alert box with the parameters inside it.

var phrase = prompt("Enter a phrase to be checked for palindrome.").toLowerCase()
var phraseBackwards = ""
for (var x in phrase) {
  phraseBackwards += phrase[(phrase.length - 1) - x]
}
if (phraseBackwards == phrase) {
  alert("The phrase you entered was a palindrome.")
} else {
  if (phraseBackwards.replace("\s+/g", '') == phrase) {
    alert("The phrase you entered would have been a palindrome, had it not had spaces")
  } else {
    if (phraseBackwards.replace(/\s+/g, '') != phrase) {
      alert("The phrase you ented was not a palindrome.")
    }
  }
}

The specific section of code that is causing trouble:

if (phraseBackwards.replace(/\s+/g, '') == phrase) {
  alert("The phrase you entered would have been a palindrome, had it not had spaces")
}

I understand that some parts of my code may not be optimal, but I'm trying to wrap things up quickly as I've procrastinated until the last minute.

Answer №1

My edit contains a few key points that should be noted.

Initially, it is essential to eliminate all non-word characters from the starting phrase using: replace(/\W/g, "")

Next step involves reversing the string:

phrase.split("").reverse().join("")

Finally, check if phraseBackwards == phrase.

It's worth mentioning that the code you initially used to reverse the string was valid. However, based on your intended use, I decided to provide a shorter alternative.

//Just an FYI - "alert(*parameters*)" will display an alert box with the specified parameters.

//Prompt user to enter a phrase and store their input.
var phrase = prompt("Enter a phrase to check for palindrome.").toLowerCase().replace(/\W/g, "");

//Create a reversed version of the entered phrase.
var phraseBackwards = phrase.split("").reverse().join("");
//Check if the new phrase is a palindrome.
if (phraseBackwards == phrase) {
    alert("The phrase you entered is a palindrome.");
}
//If the previous condition is false, execute this block.
else {
    alert("The phrase you entered is not a palindrome.");
}

Answer №2

When you reverse a phrase without any spaces, it will not be the same as the original phrase because the original includes spaces. To compare them accurately, remove spaces from both versions of the phrase. - Jeremy Thille

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

Reset the tabulator with updated data and a revised column setup on the existing DOM element

Currently, I am utilizing the tabulator jQuery plugin for a project. My goal is to re-initialize the tabulator on the same div element but with a different column configuration and dynamic data. I have provided a sample div and script below that shows wh ...

Could you please advise on how to use three.js to render Uint8ClampedArray image data?

program-image I am developing a web-based Remote Desktop Protocol (RDP) using Windows. My goal is to stream ImageData (Uint8ClampedArray) to the browser in real-time (every 100ms), and I have achieved this by utilizing server-side rendering with node-can ...

Node.js and SQL: Verify if a specific value exists in the column

In the process of developing a Discord bot using Node.js (discord.js), I have created a command named !add that requires 2 or more arguments. For example, !add Name This is the reply, where Name corresponds to args[0]. As part of my code, I check whether t ...

Encountering AngularJS promise data parsing issues

I am trying to work with promises in AngularJS. However, I encountered an error while parsing the backend response in AngularJS. What could be the issue here? This is the HTML code: <div ng-app="clinang" ng-controller="pacientesCtrl"> <a ...

Ways to reach a variable beyond a subfunction in javascript

Below is a function I have created that utilizes a GLTF loader to import a model into the scene from another class: LoadModel(path){ this.gltfLoader.load( path, (gltf) => { this.scene.add(g ...

Guide to successfully merging Mysql data with PHP into the ParamQuery Grid using Javascript

Could you please assist in converting the JSON output from MySQL into the desired format shown below? JSON [ {"storenm": "S1", "FA_SOH": "20964", "FA_CY_QTY": "15", "FA_CT_QTY": "44497"}, {"storenm": "S2", "FA_SOH": "1096", "FA_CY_QTY": "2", "FA_ ...

I'm unsure of the most efficient way to condense this statement

$(document).ready(function(){ if ($(window).width() <961){ $('.item').on('click',function(){ /*---do something---*/ }) }else{ $('.item').on('click',function(){ ...

Revising Your Task Checklist with React

I encountered an issue while attempting to update the value retrieved from Addlist. Unfortunately, my solution isn't working as expected. Additionally, clicking on the '+' button without entering any text results in an empty list being creat ...

Having difficulty changing the visibility of a div element

I am currently working on a project that involves jQuery and ASP.Net. My main goal is to create a button that can hide/show a div using jQuery. Below is the code that I have implemented: <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html PUBLI ...

vue mapGetters not fetching data synchronously

Utilizing vuex for state management in my application, I am implementing one-way binding with my form. <script> import { mapGetters } from 'vuex' import store from 'vuex-store' import DataWidget from '../../../../uiCo ...

Sorting an array of elements in JavaScript based on their value relationships

I need help grouping the elements of an array based on their inner array groupings Input: const arr = [ [123, 243], [123, 435], [736, 987], [987, 774], [123, 666], [774, 999], [098, 980], ]; Output: Result = [[123, 243, 435, 666],[736, ...

Transmitting data from Javascript to Django views

I'm looking to transfer data to my Django view while also redirecting the page. Since ajax seems to be not an option, I'm not sure how to accomplish this using Jquery. ...

Send the content written in summernote to an AJAX request

I'm having trouble with ajax and javascript, so I need to ask for assistance. Within a form, I have an editor (using summernote editor). <div id="summernote">summernote text</div> After that, I use this ajax function to send the form dat ...

Generate a fresh array from the existing array and extract various properties to form a child object or sub-array

I am dealing with an array of Responses that contain multiple IDs along with different question answers. Responses = [0:{Id : 1,Name : John, QuestionId :1,Answer :8}, 1:{Id : 1,Name : John, QuestionId :2,Answer :9}, 2:{Id : 1,Name : John, QuestionId :3,An ...

Conceal certain options by utilizing multiple select criteria

I currently have a set of 3 select objects available. Colleges <select id="collegeSelect" size="8" multiple> <option value="1" >Harvard</option> <option value="2" >Stanford</option> <option value="3" >Yale& ...

Is there a way to use the sort() function to further categorize objects that have been moved to the bottom of an array during sorting?

My task in JavaScript involves sorting within a single sort() function that is passed as a parameter. Specifically, I need to sort objects first by category and then further sort them by subcategory using: return item1.category.localeCompare(item2.catego ...

An inquiry regarding props in JavaScript with ReactJS

Check out the following code snippet from App.js: import React from 'react' import Member from './Member' function App () { const members = [ { name: 'Andy', age: 22 }, { name: 'Bruce', age: 33 }, { n ...

Erroneous Marker Placement Detected

Here is the data from my DataTable: Country Types of sales Total sales($) Name State United states of America chemicals 12662871 Obama GA Unite ...

Pause and let the asynchronous function complete without including a callback

Currently, I am in the process of writing tests for my Node.js/Express/Mongoose project utilizing Mocha and Should.js. Specifically, I am focusing on testing the functionality of my functions that interact with MongoDB. To ensure the integrity of these tes ...

What are the most effective techniques for managing headers, footers, and reusable templates in Node.js/Express views?

Currently, I've got my development environment configured with Node.JS / Express / Pug and I'm in the process of grasping the usage of views & routes. However, I seem to be struggling when it comes to embedding a "reusable" navigation bar and foo ...