Regular expressions tend to capture an extra symbol beyond what is required

How can I extract numbers from a string?

var ss = klase.match(/[col-lg-]\d+/);

When trying to extract the number, it retrieves -1 instead of just 1.

Why is this happening?

An example string:

draggable ui-draggable ui-draggable-handle dragged col-lg-8

Answer №1

In this example, the string is:

draggable ui-draggable ui-draggable-handle dragged col-lg-8

Instead of matching individual characters (using []), you want to match the exact string col-lg-#. To achieve this and capture only the number, enclose \d+ in a capture group, which can be retrieved using .match().

/col-lg-(\d+)/

This pattern should suit your requirement better.

To implement this in a script:

var example = 'draggable ui-draggable ui-draggable-handle dragged col-lg-8';
var colNum = example.match(/col-lg-(\d+)/)[1];

console.log(colNum);
// Output: 8

Answer №2

To organize your desired outcome, simply group it like this:

/col-lg-(\d+)/

For instance:

let output = 'col-lg-1'.match(/col-lg-(\d+)/),
    res = output[1]; // capture group 1 - result: 1

Answer №3

Substitute brackets with parentheses:

let result = text.match(/(col-lg-)\d+/);

Answer №4

If you are looking to verify the presence of the pattern col-lg before finding the number 1 (as indicated in your query), you can utilize the regular expression: (?=[^col-lg-])\d+. This regex ensures that col-lg- comes before the number.

To retrieve the matched result, follow these steps:

//assuming klasses contains col-lg-2 for instance

var ss = klase.match(/(?=[^col-lg-])\d+/);
var result = ss[0]; //result now holds the desired number, which is 2

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

Preventing event bubbling/propagation in custom events: a step-by-step guide

Incorporating a module-project from Github into my Angular project, I am able to resize the DOM elements that are displayed on top of a div functioning as a drawing board. To configure my initial rectangles, I am utilizing a combination of mouseDown - mou ...

How do I send a 404 error in Node JS Express when a third party API receives a bad request?

I've set up a Node JS server with a route handler that sends a request to a third-party API to retrieve a username: app.get('/players/:player', apiLimiter, function(request, response) { const player = request.params.player; const api_url = ...

Attempting to establish a login system using MongoDB

I am currently working on a function to verify user login details entered in a form and compare them with data stored in MongoDB, such as email and password. However, the function seems to be malfunctioning. The expected behavior is that when a user ente ...

When you press multiple buttons, the correct button will reveal an image while the incorrect buttons will display an X

Could you lend a hand with the code below? Your assistance is truly appreciated :). Thank you in advance. I need help setting up a functionality where clicking on the correct button (e.g. H) will display a checkmark and a forward link image. If the user c ...

Every time I try to reload the page in my comment app, all the comments mysteriously

I've noticed that my comment app is functioning properly, but the issue arises when I refresh the page and the comments disappear. Upon checking the log, it seems that the body is inserted into the comments table (it is saved). What could be going wro ...

Is it possible to utilize the Node.JS PassThrough stream as a straightforward input buffer?

In my Node.js application, I am utilizing a subprocess referred to as the "generator" to produce data. The challenge arises when the generator occasionally outputs a large chunk of data at a speed of around 50MB/s, while generally operating at a much slowe ...

What is the best way to position a rectangle on top of a div that has been rendered using

I recently started using a waveform display/play library known as wavesurfer. Within the code snippet below, I have integrated two wavesurfer objects that are displayed and positioned inside div elements of type "container". My goal is to position my own ...

Assistance with Jquery for toggling checkboxes when labels are clicked

I'm currently working on a feature that allows for checking and unchecking checkboxes upon label click. You can find my Jsfiddle here: http://jsfiddle.net/PTAFG/1/ The HTML structure cannot be altered Here is the snippet of my HTML: <div style= ...

Learn the process of uploading a default file with C# in ASP.NET

Is there a way to upload a default file from the client side without having to use the browse button in the file upload control? For example, I want to upload a specific file every time I click a button, without showing the file dialog. Can this be achie ...

The tablet is having trouble playing the mp3 audio file

When clicking on an mp3 audio file, I want the previous file to continue playing along with the new one. While this works perfectly on browsers with Windows machines, there seems to be an issue when using a tablet. The second mp3 stops playing when I clic ...

What is the significance of having a timer in a Redux reducer to prompt a re-rendering process?

Encountered some unusual behavior that I need to understand better Here is the code for my reducer. Strangely, the component linked to the redux state does not re-render with this code. Despite confirming through developer tools that the state updates cor ...

Preventing the execution of JavaScript methods with the use of the button and POST method

Unraveling this mystery: <button onclick:"javascript:cerrarPop('lightA')">Cancelar</button> fails to trigger any action. The idea of placing the button inside the post crossed my mind, but alas, the page undergoes a refreshing episode ...

Adjust the overflow to automatically decrease at regular intervals

Is there a way to make the scroll automatically move down a bit every few seconds, revealing more text in the process? Here's an example of how I want it to work: http://jsfiddle.net/Bnfkv/2/ ...

How to execute a function in store.js from a different JS file within a Vue project

I am currently utilizing Vuex to store my data in a file called store.js. Within this setup, I have a mutation method named 'autoUpdateDb' as seen below: store.js : import Vuex from "vuex"; import Vue from "vue"; import { ser ...

Disable the outer div scrolling in VueJS, but re-enable it once the inner div has reached the bottom of

I am currently working on a webpage that contains multiple divs stacked vertically. Here is the concept I am working with: Once the scrollbar reaches the bottom of the first div, the outer scrollbar will be disabled and the inner scrollbar will be enabled ...

The JSONP request connected to the user input field and button will only trigger a single time

Hello all, I'm new to this and have been searching the internet high and low to see if anyone has encountered a similar issue before, but haven't had any luck. I've been attempting to set up a JSONP request to Wikipedia that is connected to ...

Trouble with Mongoose: Data Not Being Saved

I'm encountering difficulties with a basic query on my database. While following this tutorial at https://scotch.io/tutorials/build-a-restful-api-using-node-and-express-4, the author receives a JSON object containing the name field (the only custom fi ...

[Vue alert]: Issue with rendering: "Sorry, unable to read property 'correct_answer' as it is undefined"

My code fetches data from an API. The questions display correctly, but the answers cause an error that crashes the app. Initially, the code worked fine in App.vue, but moving it to a different view page caused the crash. Any suggestions on how to fix this ...

Verifying Custom ac.uk Email Addresses in ASP.NET C#

Is there a way to modify the regular expression validation in ASP.NET C# for email addresses ending with ac.uk? I need users to register using their work email addresses that have the ac.uk domain. \w+([-+.']\w+)@\w+([-.]\w+).&b ...

npm build issues stemming from browserlist configurations

I am encountering an issue with my create-react-app failing to build, showing the following error: ./src/index.css Module build failed: BrowserslistError: Unknown browser query `dead` at Array.forEach (<anonymous>) I have carefully reviewed my ...