Unusual behavior observed in Javascript Regexp while attempting to match non-whitespace characters, exemplified in a functioning

I find myself puzzled by certain aspects of RegExp. Can anyone offer some insight? Could there be hidden words within RegExp that cause a failure to match? My suspicion is that the sequence "slt" contains a clandestine symbol that sabotages the success of the RegExp.

Here's a demonstration to experiment with: click here for demo

//this doesn't work
var funcArgString="c09__id slt ccc";
var myRegExp = new RegExp("([^ \s]*) ([^ \s]*) ([^ \s]*)","g");
alert(myRegExp.exec(funcArgString));

//this works... but why?
var funcArgString="c09__id abcdefg ccc";
var myRegExp = new RegExp("([^ \s]*) ([^ \s]*) ([^ \s]*)","g");
alert(myRegExp.exec(funcArgString));

//this also works
var funcArgString="c09__id slt ccc";
var myRegExp = new RegExp("(.*) (.*) (.*)","g");
alert(myRegExp.exec(funcArgString));

Answer №1

If you wish to include a backslash \ in your regular expression, you must use double backslashes \\ when passing the expression as a string:

var myRegExp = new RegExp("([^\\s]*) ([^\\s]*) ([^\\s]*)","g");

The backslash serves as an escape character in JavaScript strings and will be treated as such. To insert a literal backslash, you need to escape it with another backslash.

It's important to note that the extra space in the character group can be omitted since \s already covers it.

If you only use one backslash, this is what your resulting expression would look like:

> new RegExp("([^\s]*) ([^\s]*) ([^\s]*)","g");
  /([^s]*) ([^s]*) ([^s]*)/g

My guess is that the slt contains some hidden secret james bond symbol causing the regexp to fail

Indeed, the culprit here is the letter s ;) Using ([^s]*) matches any character except for an s, hence why the first string isn't matched.

Updated DEMO

Alternatively, you can utilize a regex literal. Since it's not within a string, there's no need to escape the backslash:

var funcArgString="c09__id slt ccc";
var myRegExp = /([^\s]*) ([^\s]*) ([^\s]*)/g;
alert(myRegExp.exec(funcArgString));

Answer №2

Instead of utilizing [^\s], you have the option to opt for \S, as it serves the same purpose.

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

Shader designed to maintain the original lighting of the landscape

Currently, I have a shader set up to mix various textures for my terrain such as grass, sand, and rocks. While the blending is working well, the issue arises with compatibility with Three.js lighting engine. All vertices appear overly bright due to this ...

Steps for transforming 112889 (in mmddyy format) into 11/28/89 or 11/28/1989

Is there a way to convert the unformatted date 112889 (mmddyy) into a specific format like 11/28/89? console.log(new Date('112889')) // The output I'm getting is: Sat Jan 01 112889 00:00:00 GMT+0800 I've searched extensively on Google ...

Perform batch updates on multiple documents using MongoDB

How can I efficiently update multiple documents in MongoDB by iterating through an array of objects and then returning the modified documents in the response? Be sure to refer to the code comments for guidance .put(function (req, res) { var data = r ...

Prevent the user from selecting an option if the value is already present

In the process of creating a library membership form, I am utilizing an ajax request to populate the student list in a select option. The goal now is to disable the options for students who are already members of the library. View of the Form <div cla ...

Can someone provide a method to access the namespace of an Angular controller when utilizing the "Controller As" format?

Imagine you have an AngularJS ngController directive set up like this: <div ng-controller="SomeCtrl as herpderp">…</div> Is there a way to extract the namespace ("herpderp") from within the SomeCtrl controller itself? This could be useful f ...

Nextjs compilation error - Unable to locate module: Cannot resolve 'module'

Currently, I am immersed in a nextjs project using wagmi hooks. Recently, Nextjs presented me with an error message indicating that it cannot resolve the 'module' (refer to the error message below). This occurred after resolving the initial error ...

Error: Unable to access length property of null object. Can you explain this to me?

One of my questions that I'm trying to solve is about the error message "Cannot read properties of null (reading 'transition'). What does it mean?". I tried using the solution suggested in this question on integration of 'mychart.update ...

The request to login at the specified API endpoint on localhost:3000 was not successful, resulting in a

As I continue to develop my programming skills, I have been working on configuring a database connected with nodejs in the same folder. However, when trying to make an ajax request to the database, I encountered an error indicating that the database may be ...

React: How to Close a Modal in a Child Component Using the Parent Component

In a scenario where I have a modal in a child component that manages a delete function in the parent component, it seems like the most appropriate choice to have the child component hold the state of the modal (whether it is open or closed). Parent Compon ...

Validating the accuracy of Membership.GeneratePassword

I've encountered an issue when using Membership.GeneratePassword() to create random passwords. Sometimes the generated password does not meet the required validation criteria, especially if a user can input their own password. My goal is to ensure th ...

Synchronizing jQuery parameters

I have developed a JavaScript shopping basket where the total sum updates automatically when a quantity is selected. However, I encountered an issue where the total value does not update when a product is removed unless the page is refreshed. Here's ...

Learn how to utilize the combineLatest/zip operators to only respond to emissions from the second observable while disregarding emissions from the first observable

Here's an example of how I'm initializing a property: this.currentMapObject$ = zip(this.mapObjects$, this.currentMapObjectsIndex$, (mapObjects, index) => mapObjects[index]); I want the value of this.currentMapObject$ to be emitted only ...

Nested within an it block are Protractor Jasmine describe blocks

Initially, the code provided below appears to be functioning properly. However, I have not come across anyone using this method before, leading me to question its validity and potential unforeseen drawbacks. The scenario involves writing an end-to-end tes ...

Troubleshooting issues with NodeJS server and client connectivity on Cpanel

I've successfully created a nodejs application that functions as a websocket server and serves a basic client webpage. The websocket is running on port 8080, and the client connects through wss://192.168.3.101:8080 when tested locally. However, when I ...

Ways to loop through an array in a JSON object

Exploring methods of iterating through an array in json: $(document).ready(function(){ $('#wardno').change(function(){ //this code will execute whenever there is a change in the select with id country $("#wardname > ...

"Double the Data: A D3.js JSON Tale of Two Creators

I found inspiration from this example: http://bl.ocks.org/mbostock/1062288 to create a collapsible Force Layout. One challenge I'm facing is how to display a graph where a single node is connected to two parent nodes. father father | | ...

Is there a way to obtain cookies on a Server-side component in the latest version of Next.js?

import axios from "axios"; const Api = axios.create({ baseURL: "http://127.0.0.1:5000", }); axios.defaults.headers.common["Authorization"] = cookie; In server-side environment, document.cookie is not accessible. Alternat ...

Issue with Firefox: JQuery-UI checkboxes failing to be selected when using Shift or CTRL keys

UPDATE: After reviewing mark.hch's response, I discovered that this issue only occurs on Firefox. To clarify my previous explanation: I am not seeking assistance with the event handler - it was just provided as context. My specific requirement is for ...

"Encountered an error while trying to access properties that

Struggling to create a practice menu with the functionality of making elements appear and disappear on click? If you are encountering issues with a class named "option" not working as expected, you are not alone. Clicking on nested objects like images or i ...

An error with jQuery occurred in the client's post response, resulting in a 400 POST HTTP/1.1 error

I am struggling to identify the issue with my code, especially since I'm not very familiar with jQuery. The goal is to create an HTML form for storing car data based on this template: https://i.sstatic.net/u40nG.gif The source code for the HTML form ...