What is the best way to extract percentage values from a string using a regular expression?

Is there a way to extract percentage values from a string without including the percent sign?

I am trying to retrieve the numbers from the string, excluding the % symbol. Currently, my code works but includes the percent sign in the output:

"asfd %1.3344 %1.2323 % asdf %".match(/%[0-9.]*/g)

Result:

["%1.3344", "%1.2323", "%", "%" ]

But I want the result to be [ 1.3344, 1.2323]

I attempted using a regex look ahead, but it didn't work as expected and returned an array of empty strings:

"asfd %1.3344 %1.2323 % asdf %".match(/(?=%)[0-9.]*/g)

result: ["", "", "", "" ]

Answer №1

"Discovering the magic within strings - extracting numerical values using JavaScript regex".match(/%[0-9.]+/g).map( function (item) { return item.substr(1); })

Answer №2

To solve this issue, the common approach is to group the desired content and utilize exec within a loop:

var re = /%(\d+(?:\.\d*)?)/g;
var percentages = [];
var m;

while(m = re.exec(str)) {
    percentages.push(+m[1]);
}

It's worth noting the stricter regular expression used: it looks for at least one digit, followed by an optional decimal point and any number of additional digits.

Answer №3

I think this approach will also solve the problem.

Sample JavaScript code snippet:

var str = "This is a sample string with %1.3344 some numbers %1.2323 % included",
    arr = [];

str.replace(/%(\d+(?:\.\d*)?)/g, function (match, number) {
    arr.push(number);
});

console.log(arr);

Check out this jsFiddle for demonstration

Answer №4

After doing some research, I came across a possible solution:

var str="asfd %1.3344 %1.2323 % asdf %";
var patt=/%([0-9\.]+)/g;
var result;
while(null != (result = patt.exec(str))){
    document.write(result[1] + '<br />');
} 

Answer №5

This particular regular expression seems to be quite effective in this scenario without the need for a loop.

var str = "asfd %1.3344 %1.2323 % asdf %", resultsArray;
resultsArray = str.replace(/(^[^%]+)|[^\d .]|( (?!%\d))/g,'').split(' ');

By using the Split String method, you can obtain an array of values.

If there are other types of patterns that may appear in your input (such as consecutive dots like "asfd %1.. %1.23" or any other variations), please inform me so we can adjust the regular expression accordingly.

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

Can you explain the functionality of the NextSibling method?

I have a question about how the property NextSibling behaves when using the method getElementsByClassName(). Let me illustrate the issue with this code example: function Sibling() { var x = document.getElementsByClassName('firstClass')[0]; ...

Retrieve the value of an attribute within a controller function that is not a directive

Here is some HTML content, <button data-href="helloworld">Show href Value</button> And here is some Javascript content, $("body").on('click', 'button', function(){ console.log($(this).attr("data-href")); }); When exe ...

Establish a trigger in mongoDB that monitors changes in document values and triggers an email notification

Hello there! As a newcomer to MongoDB and the world of web development, I have a question that I hope you can help me with. I am looking to send out emails based on the time difference between the current time and the event time stored in the event model a ...

Implementing Google Maps on a webpage with a dynamic drop-down form using a combination of Javascript and PHP

On my HTML page, I have two drop-down lists populated with data from a MySQL database including latitude, longitude, and address. The user selects an item from the first drop-down and clicks submit. Upon submission, I want to display a Google map with a m ...

Encounter issue with async function in produce using Immer

Having an issue while attempting to create an asynchronous produce with immer. When calling the async function, this error is encountered: Below is my code snippet: import { combineReducers, createStore } from 'redux'; import produce from ' ...

Retrieving key-value pairs from a Json string through regular expressions

After converting a Json to a string, I need to extract a specific key pair value. For example, the original Json looks like this: { "key1": "value1", "key2": "value2" } I want to extract the key pair value for "key1": "value1" "key1": "value1" ...

A guide on invoking an onclick function within a Template literal in React.js

I am seeking assistance with implementing an on-click function using template literals in React JS. When a button within the template literal is clicked, I want to trigger another function in React JS. addPopupToLayer = (surface, layer) => { cons ...

The output does not show the response from the method in React Native

I am facing an issue with a method in my code (React Native). I have an array of IDs and I need to send a 'GET' request for each ID to display a preview card for each. To achieve this, I have used the 'map' method on my array. The req ...

What is the best way to incorporate an image zoom-in effect into a flexible-sized block?

Having a fluid grid with 3 blocks in one row, each set to width:33.3%. The images within these blocks are set to width: 100% and height: auto. I am looking to implement a zoom-in effect on hover for these images without changing the height of the blocks. I ...

Using the prop callback in a React test renderer does not trigger updates in hooks

I am currently exploring ways to effectively test a React function component that utilizes hooks for state management. The issue I am encountering revolves around the onChange prop function not properly updating the state value of my useState hook. This in ...

Having trouble connecting to the Brewery API, could use some guidance from the experts (Novice)

I'm currently facing some difficulties connecting to a brewery API (). I am developing a webpage where users can input the city they are visiting and receive a list of breweries in that city. As someone unfamiliar with APIs, I am unsure about the nece ...

Executing AJAX requests to trigger a function in a separate MVC controller using Jquery

Below is the structure of my folders. Both of these folders are located within the Area folder. https://i.sstatic.net/KLGzl.png I'm currently attempting to invoke a function from the EmailController inside ITRequests/Scripts/Edit.js, but it's u ...

Filling dropdown menu with data from document elements

Currently, I am developing a Java application that is connected to MongoDB for managing film data. One of the features I want to include is a ComboBox that displays the names of films stored in the database. However, my issue lies in populating the ComboBo ...

What is the best way to incorporate a countdown timer on an ASP.NET webpage?

Looking to display a countdown timer in the top right corner of my ASP page that starts from 00:00:30 and counts down to 00:00:00 before resetting back to 00:00:30. Does anyone have any suggestions on how to achieve this? ...

AngularJS and ExpressJS clash in routing (Oops, Crash!)

When setting up routing in angularjs and expressjs, I have created app.all('/*'...) to enable rendering index.html. However, whenever I use /*, the page crashes with an "Aw, Snap!" message. angularjs home.config(function($routeProvider,$locatio ...

Issues with functionality arise when cloning HTML divs using JQuery

VIDEO I created a feature where clicking a button allows users to duplicate a note div. However, the copied note does not function like the original - it's not draggable and changing the color of the copied note affects the original note's color. ...

I am currently developing a user-friendly bug reporting system that is fully functional. However, I have encountered a persistent error message in the console related to Discord.js that I am determined to resolve

In coding this bot, we are using the Discord.js library and some custom functions to handle bug reports from users. The bugreport command allows users to submit their reports, which are then sent to a specific channel for further action. However, we encou ...

"Efficient Ways to Manage Various File Types in React: xlsx, pptx, doc, docx

I am encountering an issue with downloading files in my React application. The API is functioning properly as confirmed using Postman, where different file formats such as xlsx, pptx, doc, docx, ppt and xls can be downloaded and opened successfully. Howev ...

Error encountered in jQuery call during Page_Load

Here is the code I am using to register a javascript function on Page_Load (I also tried it on Page_Init). This javascript function switches two panels from hidden to shown based on a parameter when the page loads: protected void Page_Load(object sen ...

Using the hash(#) symbol in Vue 3 for routing

Even though I am using createWebHistory, my URL still contains a hash symbol like localhost/#/projects. Am I overlooking something in my code? How can I get rid of the # symbol? router const routes: Array<RouteRecordRaw> = [ { path: " ...