What is the meaning of a word character in a character class?

\w - represents the character class [A-Za-z0-9_] Character class

Despite this, I find it difficult to grasp how it is interpreted within a character class.

When I use

[\w-~]

let test = (str) => /^[\w-~]+$/.test(str)

console.log(test("T|"))

it fails for T|

However, if I use

[A-Za-z0-9_-~]

let test = (str) => /^[A-Za-z0-9_-~]+$/.test(str)

console.log(test("T|"))

it returns true,

I am puzzled by how these two expressions differ from each other?

Answer №1

In my perspective, the primary distinction between your two instances lies in the positioning of the hyphen character. What transpires is as follows:

let check = (str) => /^[A-Za-z0-9_-~]+$/.test(str)

console.log(check("T|"))

Here, it's construed as a range:

let check = (str) => /^[_-~]+$/.test(str)

console.log(check("|"))

This will result in true.

On the other hand:

let check = (str) => /^[\w-~]+$/.test(str)

console.log(check("T|"))

Due to \w representing a set of characters on its own, it interprets the hyphen character independently.

The placement of the hyphen and its neighboring elements can greatly alter its interpretation.

To prevent such predicaments, you can reposition it at the end like this:

let check = (str) => /^[A-Za-z0-9_~-]+$/.test(str)

console.log(check("T|"))

This will yield a result of false.

Answer №2

It appears that the key factor here is the range being used, specifically when utilizing the expression ^[A-Za-z0-9_-~]+$

The characters _-~ represent a range between _ (index 95) and ~ (index 126) in terms of ASCII values (case sensitive). This explains why T| is matched and returns true. However, if you were to use ^[\w-~]+$, it does not establish a specific range like _-~, causing it to fail and return false.

Similarly, ^[A-Za-z0-9-~]+$ also results in false because it lacks the inclusion of the _ character necessary for creating the _-~ range between _ (index 95) and ~ (index 126).

let test = (str) => /^[A-Za-z0-9-~]+$/.test(str)

console.log(test("T|"))

For further clarification, refer to https://regex101.com/r/vbLN9L/5 in the EXPLANATION section.

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

Trigger a page refresh using a popup

Exploring the world of React for the first time has been quite a journey. I've encountered a hurdle in trying to force my page to render through a popup window. The setup involves a function component with a popup window that allows text changes on t ...

What are the steps to modify the sign in page on keystone.js?

I recently started using keystone.js and I'm having trouble locating the sign in page within the files. I've searched through all of the keystone.js files but can't seem to find where it's written. Can someone please guide me on how to ...

Inquiring about socket.io: How can an io emit its own signal?

I am currently working on implementing the emit event in an express router, and I'm attempting to pass a global.io variable. However, I've encountered an issue where despite adding the following code: io.emit('join','Tudis' ...

Contrast between pm.response.json() and parsing the responseBody using JSON.parse()

Can you explain the key distinction between const json_response = pm.response.json() and json_response = JSON.parse(responseBody) ...

Replacing default hover behavior from an external library

Currently, I am utilizing a JS library that comes with a specific widget. Basically, I have the following list (I removed unnecessary DOM code): <li class="disabled"> When I hover over this list item, it turns into: <li class="disabled state-a ...

I encountered an error with no matching overload when attempting to make a call using the Tanstack query function

While I was successfully calling a single data in my database using the useEffect hook, now I am attempting to learn how to use tanstack@query. Unfortunately, I encountered an error when trying to call it. No overload matches this call. Overload 1 of 3, ...

Tips for accessing the FormControlName of the field that has been modified in Angular reactive forms

My reactive form consists of more than 10 form controls and I currently have a subscription set up on the valueChanges observable to detect any changes. While this solution works well, the output always includes the entire form value object, which includ ...

Navigating redirects in Node.JS using HorsemanJs and PhantomJS

I've recently delved into using horseman.js for web scraping in node.js. However, I'm facing difficulty understanding its working mechanism and finding useful examples online. My primary objective is to log in to a platform and extract specific ...

Transferring user-selected values from JavaScript to a PHP file

When sending values from JavaScript to a PHP file, everything works smoothly when all the values are collected. Step1 functions perfectly as both fields are mandatory. However, in Step2, values are only sent when all the fields are selected. There are co ...

Eslint is signaling an error when the keyword "async" is used in the most recent version of Node for Firebase Functions

I'm venturing into using Firebase Functions for my project, but as a newcomer to Javascript, I've been struggling for a week now and hit a roadblock with the following issue. Below is the snippet of my code: exports.postcleanup = onSchedule("eve ...

Is it feasible to activate an action on a click of a Vimeo video?

Is there a way to activate an event by clicking if a video is set with background=1 and has no controls? This particular video is from Vimeo, using a plus account which allows for setting background=1. The scenario involves a Vimeo video playing on loop ...

HeatMap Visualizations Data

I have a HeatMap calendar project () where I am attempting to populate it with dynamic data. My approach involves extracting various dates from a file and converting them into milliseconds in order to create the necessary key-value pair for the calendar. ...

Passing data between multiple components in Vue.js and Laravel: Best practices

require('./bootstrap'); window.Vue = require('vue'); Vue.component('exampleComponent1', require('./components/exampleComponent1.vue')); Vue.component('exampleComponent2', require('./components/exampl ...

Is there a conflict between bootstrap.min.JS and chart.min.js?

I have been working on developing an admin page for customer support and I recently added a visually appealing chart to display some data on the home screen. The chart integration was successful, but when I introduced tab panes to the page and refreshed ...

Vue's v-on:click feature stops functioning correctly post-build

I have successfully integrated the Vue slide example from this link into my Angular template. Everything works fine when running ng serve, but after building with ng build and then trying to start it again with ng serve or from the dist folder using npm s ...

Troubleshooting issues with Firebase integration in a Node.js environment

I am currently encountering difficulties implementing Firebase in my Node.js project. Below is the code snippet that I am attempting to execute on Node. var firebase = require("firebase"); var admin = require("firebase-admin"); var serviceAccount = requi ...

Press the body to update state in React and close the dropdown

Seeking a solution for closing a dropdown menu when a user clicks outside of it or on another element? Consider the following code snippet written in React: var Hello = React.createClass({ getInitialState() { return { openDropdown: false ...

What location is optimal for storing ng-templates within an Angular/Django single-page application?

My project involves using Django and AngularJS to create a single-page application. I have numerous ng-templates structured like this: <script type="text/ng-template" id="item.html"> // content </script> Currently, all these templates are l ...

Sequence jQuery functions so that each one only runs when the previous one has finished

I want to have more control over the order of my functions in jQuery. When I click on an element, I would like an image to fade out, change its source, and then fade in the new image. The code I currently have kind of works, but it performs all these acti ...

What is the process for accessing a user's followers and users they are following using the new Spotify Web API?

Having just checked out the latest Spotify API documentation, I'm curious about how to access information on a user's followers and following. Is there a way to retrieve this data using the new Spotify Web API? I am looking to make requests to t ...