Differences between JavaScript array manipulation using the split(" ") method and the spread operator

I'm currently attempting to determine if a given sentence is a palindrome, disregarding word breaks and punctuation.

The code snippet that utilizes cStr.split(" ") DOES NOT achieve the desired outcome. Although it splits on whitespaces (" "), calling reverse() seems ineffective in this case.

const palindromes = (str) => {
    const regex = /[!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~]/g;
    const cStr = str.toLowerCase().replace(regex, "").split(" ").join("");
    const revStr = cStr.split(" ").slice().reverse().join("");
    return cStr === revStr ? true : false;
};

FURTHER CONSIDERATIONS: Upon joining the original string cStr at the end, the characters appear collapsed. In the flawed code example, splitting on "whitespace" (split(" ")) triggers the script to halt without throwing any errors?

The same logic applied with either [...cStr] or cStr.split("") DOES yield the intended result:

const revStr = cStr.split("").slice().reverse().join("");

// or
const revStr = [...cStr].slice().reverse().join("");

How does the choice of "separator" - /""/ or /" "/ impact this behavior?

If the separator is an empty string (""), the string is converted into an array of individual UTF-16 "characters", excluding empty strings at the ends.

Linked inquiry regarding array manipulation: reverse-array-in-javascript-without-mutating-original-array

Related query concerning string handling: character-array-from-string

Documentation for Split(): String.prototype.split()

Answer №1

It appears that you have reviewed the documentation for string.split, but may not have fully grasped its nuances. When splitting a string with a separator that does not exist in the string, it returns an array with one element containing the entire string. However, if you split by an empty separator, it will divide the string after every character.

let astring = "nowhitespacehere";
let splitstring1 = astring.split(" ");
console.log(splitstring1);
let splitstring2 = astring.split("");
console.log(splitstring2);

Your initial method removes all white spaces from the string using

str.split(" ").join("");

Later on, you perform

cStr.split(" ").slice().reverse().join("");

If you break down those steps:

  1. .split(" ") by whitespace. Since there are no whitespaces, this results in an array with one element: [cStr]

  2. You .slice() this array, creating another 1-element array: [cStr]

  3. You .reverse() this 1-element array, yielding yet another 1-element array: [cStr]

  4. You finally .join("") the elements in this 1-element array with an empty separator to obtain cStr

In your alternate approach, you execute

cStr.split("").slice().reverse().join("");

The key distinction is the initial split("") which splits the string after every character

Your first method does not "stop executing"; rather, it behaves as instructed - splitting by a non-existent separator. There is no reason for this action to throw an error, as it follows the intended functionality of the split method. It concatenates characters until a separator is found, and if none exists, the entire string becomes the token...

Answer №2

After reviewing your initial function and looking through @derpirscher's response, I made some optimizations to enhance its efficiency. I didn't want to discard it completely, so here are my thoughts as additional inspiration.

When dealing with palindromes, the comparison is at the letter level, eliminating the need to break the sentence into individual words.

const checkPalindrome = (str) => {
    const regex = /[^a-zA-Z]/g; 
    const cleanStr = str.toLowerCase().replace(regex, ""); 
    const reversedStr = cleanStr.split("").reverse().join("");
    return cleanStr === reversedStr; 
};

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

Creating arrays in Python 3: A Beginner's Guide

I am struggling to declare an array in Python3 and keep encountering errors. Python 3.6.7 (default, Oct 22 2018, 11:32:17) [GCC 8.2.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> numbers=[] >>> num ...

Is there a way to clear the search box in a wenzhixin bootstrap table without refreshing the page when clicked on?

Is there a way to clear the search box in a wenzhixin bootstrap table without refreshing the page when clicking anywhere on the page? <table id="view_table" data-toggle="table" data-search="true" data-page-list="[5, 10, 20]" data- ...

Achieving Automatic Scrolling of Drawer in Material UI React JS

Looking for assistance, can anyone lend a hand with this code snippet I've been working on? See it here: https://codesandbox.io/s/5xoj9zw56l I referenced this code as part of my project development: https://codesandbox.io/s/6jr75xj8y3 ...

The view in my node is rendering a different ejs view, and I have verified that the path

Currently, I am using the render method for a view in EJS. The path is correct but the view in the route is an old one that I used for testing purposes. This is my server.js code: https://i.sstatic.net/Xl1Ct.png Here is my route: https://i.sstatic.net/ ...

Passing arguments to an external function in jQuery from a dynamically loaded Ajax page

Despite its confusing title, the issue at hand is actually quite simple. My homepage contains a script that loads an external PHP file for a specific section of my website. Within this PHP file, I need to call a function from the main JavaScript file (th ...

Efficiently loading an image in one go

Rendering approximately 3000 records, each row displays: Customer Profile Edit Customer Name, Action 1 John Edit image | Delete image 2 John Edit image | Delete image 3 John Edit image | Delete image 4 John ...

The message vanishes upon refreshing the page

I've developed a socket.io web app. When I click on the button to send a message, the message appears briefly but disappears when the page refreshes unexpectedly. How can I prevent this random refreshing and ensure that socket.io saves my messages? B ...

Encountering an issue with using third-party APIs due to receiving an error message stating that the requested resource does not have the 'Access-Control-Allow-Origin' header

My current challenge involves attempting to access a third-party API using AngularJS. Interestingly, I only encounter this issue in Chrome, as it works perfectly fine in IE. The error message that pops up reads as follows: XMLHttpRequest cannot load https ...

The filter predicate function is failing to produce a result and the following error occurs: Unable to access the 'data' property in MatTableDataSource within

There seems to be an issue with the function that is causing it to not work correctly the first time a letter is entered in the search bar. It returns nothing in the array initially, but works fine when letters are removed and typing continues. createFilt ...

Is there a way to extract the text from the inner div of an element using nightwatch.js?

I'm attempting to retrieve the content of a cell within a table, with the following CSS structure: <div data-testid="cellvalue_row-1_col-0" class="Table-cellContent" xpath="1"><span data-testid="tableCellCon ...

I am having difficulty accessing the new values in the main function

//A unique code snippet for generating all possible binary strings of a specified length. #include<stdio.h> #include<stdlib.h> char a[20]; int ind = 0; void generateAllBinaryStrings(int n, char **arr,int `i){ if (i == n){ printf("%s &bso ...

Tips for displaying specific HTML elements in AngularJS using ng-repeat and ng-if

I am working with some bootstrap HTML code that includes an ng-repeat function. <div class="row"> <div class="col-lg-4" ng-repeat="p in persons"> <img class="img-circle" src="images/{{ p.image }}" width="140" height="140"> < ...

What is the best way to store values from dynamically generated input fields into a single database column?

In my application, I have implemented 2 dynamically added input fields. My goal is to insert the values from these two fields into separate columns in the database. <div class="form-group "> <div id="itemRows" class="col-md-12"> & ...

Delete the click event listener that was previously assigned by a different script

After extensive investigation using the Chrome developer tools, I have identified a click event listener that needs to be removed: https://i.sstatic.net/dnB3Q.png I successfully removed the listener using the developer tools. Further analysis revealed th ...

Joi mistakenly demanding certain fields that should not be mandatory

I've encountered an issue with posts validation using @hapi/joi 17.1.1. In my schema, I have two fields: textfield and picture. Although both fields are not required, the validation is still indicating that the picture field is mandatory. posts valid ...

Is the removal of the Vue-Router link happening when you click on the top app bar icon in Google Material

Review of the following code snippet: <!DOCTYPE html> <html> <head> <title>test</title> <meta content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0' name='vie ...

Tips for correctly mapping a shuffled array in React/Next without triggering a hydration mismatch error

I've been working on a Next.js website and I'm trying to display a randomized list of famous quotes. To achieve this, I'm using lodash to shuffle the array of quotes and then mapping them onto the page. import { useMemo } from 'react&ap ...

Guide to encoding data using a multidimensional array in JSON format

I have an array that looks like this: array { [0] => {"ID":"343","name":"John","money":"3000"} [1] => {"ID":"344","name":"Erik","money":"2000"} [2] => {"ID":"346","name":"Ronny","money":"3300"} } My goal is to transfer this data from ...

Controlling the angular bootstrap modal form with ease

I am having trouble accessing the form in the modal controller (Plunkr). The variable myForm doesn't seem to be accessible. How can I make the alert call work correctly: angular.module('plunker', ['ui.bootstrap']); var ModalDemoCt ...

Application with Single Page design has a Large DOM, leading to sluggish performance

I've been working on a single page application that heavily relies on widgets like grids and tabs from the jqWidgets library. These widgets are all loaded when the page is first opened. However, I've noticed that after interacting with the site f ...