In JavaScript, you can use regular expressions to group the characters `**` along with the

If I want to use JavaScript RegExp to match an expression string, how can I do it effectively?

For example: '1**2*3+4' ->

['1', '**', '2', '*', '3', '+', '4']
, rather than
['1', '*', '*', '2', '*', '3', '+', '4']

Is there a way to achieve this using the following RegExp pattern?

'1**2*3+4'.match(/[*\/+-]|\d+/g)

Additionally, is it possible to group (\*\*) together with +-*/ in brackets without making them stand out individually like: /\*\*|[*\/+-]|\d+/g

Answer №1

To match one or more asterisks separately from the character class, you can use the following regex pattern: \*+. This will allow you to find instances of * without mixing with other characters like /, +, and -.

[\/+-]|\*+|\d+
  • [\/+-] - Matches either /, +, or -
  • | - Or
  • \*+ - Match one or more occurences of *
  • | - Or
  • \d+ - Match one or more digits

Check out the regex demo here

let s = '1**2*3+4';
console.log(s.match(/[\/+-]|\*+|\d+/g));

If you want to also include matching +- as a single entity, you can repeat the character class by itself in the regex pattern.

[*\/+-]+|\d+

Here is a demo for this regex pattern

Answer №2

To capture a double-character inside the square brackets (as they are shorthand for single character OR), you must modify the regex pattern accordingly. Here is an example of how to achieve this:

/\*\*|[*\/+-]|\d+/g

The reason why this pattern captures ** is because \*\* appears before the single * in the bracket sequence.

Alternatively, if you wish to match any repeating special characters as individual groups (e.g., // should be matched as // instead of /,/), you need to expand the bracket options into separate | patterns and include + (indicating one or more occurrences of the preceding character) after each:

/\*+|\/+|\++|\-+|\d+/g

This expression instructs the regex engine to "match all instances of at least one *, at least one /, at least one +, at least one -, or at least one digit."

If you want to limit the matching to up to 2 occurrences of each character, you can substitute each + with {1,2}.

Answer №3

Implement a personalized quantifier:

'1**2*3+4'.match(/[*\/+-]{1,2}|\d+/g)

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

Updating state before and after making an API request

I have implemented an asynchronous function with prevState in my code. The purpose of using prevState is twofold: 1) updating a deeply nested object and 2) sending data to an API based on the current state. Asynchronous programming is utilized for the API ...

What is the best way to provide a static file to an individual user while also sharing its file path

I have integrated jsmodeler (https://github.com/kovacsv/JSModeler) into my website to display 3D models. Currently, users can only select a file using a filepicker or by entering the path in the URL (e.g., http://localhost:3000/ModelView#https://cdn.rawgit ...

Retrieve JSON data from Form Submission

While I am not a front end developer, I have been trying my hand at it recently. I hope that the community here can assist me with an issue I am facing. I have a form that is supposed to send files to a server-side API like shown below: <form id="uploa ...

Having trouble retrieving response content in Mithril

I've been experimenting with making a request to a NodeJS API using the Mithril framework in my client application. I attempted to fetch data by following their example code: var Model = { getAll: function() { return m.request({method: "G ...

Utilizing a TinyMCE editor within a text area and implementing a posting form through ajax

I am currently using tinyMCE in my textareas and submitting my form through AJAX. However, I am facing an issue where the value in the textarea is not being recorded when I try to save it. This is my text area: <textarea class="form-control" name="cont ...

the event listener for xmlhttprequest on load is not functioning as expected

I am facing an issue with validating a form using JavaScript and XMLHttpRequest. The onload function is supposed to display an alert, but it only works sometimes. I'm struggling to identify my mistake. document.getElementById("button").addEventListen ...

The Authorization header in POST and PATCH fetch requests is stripped by Typescript

I have developed an API in C# that utilizes JWT tokens for authorization. On the frontend, I store these tokens in local storage and retrieve them when making a request. GET or DELETE requests work seamlessly, as I can verify through console.log() that t ...

Error occurs when trying to map an array within an asynchronous function

Hey there, I have an array of objects with validation inside my async function (router.post()) and I need to map it before validating. Here is the approach I am taking: ingredients.map(({ingredient, quantity})=>{ if(ingredient.trim().length < 1 | ...

What is the best way to make a vertical line using the CSS code provided in the link?

Check out this cool horizontal line design I found on stackoverflow: Click here for CSS code to create the line I really like the look of the line. Here's how I implemented it on my website: hr.fancy-line { border: 0; height: 5px; } hr ...

Issue with MVC 4 Asynchronous File Upload: Controller Always Receiving Null Value

I'm encountering an issue while attempting to upload a file asynchronously from ajax to my controller. I am passing 3 variables - PictureId, PictureName, and PictureFile. The problem specifically lies with the "PictureFile" variable as it consistently ...

Tips for concealing broken images in jQuery/JavaScript when generating dynamic content

Is there a way to hide the broken images in this dynamically generated HTML code using JavaScript? Unfortunately, I don't have access to the source code itself. I'm new to JQuery and could really use some assistance. Below is the snippet of the ...

Error Encountered in .then Method with Vue.js

I am working on a GET request that determines whether the user is an Admin or not. The challenge I am facing is that I need to show a button using the v-if directive to verify if the value is true or false. By default, the value is set to false. Informati ...

Is there a way to eliminate a div and all its contents from the DOM?

As I work on my web application, I am trying to implement a system where error messages can be returned via ajax upon success or failure. The ajax script is functioning correctly in terms of returning errors or successes. However, my challenge lies in com ...

Having issues with my JavaScript timer - seeking assistance in troubleshooting the problem

Trying to set a timer for my little game, but facing some difficulties. The timer causes the balance to randomly increase from 0 to 13000 + some extra amount. <script> var coins = 0; var speed = 1; </script> <center> <h4> ...

The function 'create' is not a recognized property within the 'Completions' type

Recently, I've been experimenting with ChatGPT and have just installed the latest version 4.8.0. My current project is built on NextJS. Prior to this, I successfully completed a project using v3.something last month, but I'm encountering diffic ...

an unsuccessful attempt to retrieve data was made

After using the fetch function to retrieve a list of notes, nothing appears when I console.log it. I have double-checked the URL and it is correct. Here is the code snippet: import React, { useState, useEffect } from 'react' const NotesListPage ...

Struggling to pass state values between React components

I'm having trouble passing the state of my functions through. I've included {state.name.user} and {onInputChange}, but I keep encountering errors. <Navigation isSignedIn={isSignedIn} onRouteChange={onRouteChange} /> { route === ...

Incorporating a new element into a JavaScript array

I recently used a vue.js library that has a specific requirement for arrays in this exact format autocompleteItems: [ { text: "Python" }, { text: "HTML" }, { text: "CSS" }, { text: "React ...

Finding the location of a file within a published web component

I am currently working on a webcomponent where I need to include a link tag in the head section and set the href attribute to a folder within a node module. At this stage, during the development of my component, my project structure looks like this: http ...

Is it possible to incorporate variables when updating an array or nested document in a mongodb operation?

Within the "myCollection" target collection, there exists a field named "japanese2". This field is an array or an object that contains another object with a property called "japanese2a", initially set to 0 but subject to change. My goal is to update this p ...