Using JavaScript to utilize a variable containing a .match method with Regex Expression

Recently, I started delving into the world of regex with the aim of incorporating variables in my matches.

Imagine I have a string that reads "Total: $168" My goal is to extract just the numerical value; 168.

This is what I currently have:

totalCost = totalCost.match(/[^Total: $]*$/);

When I display the result, it indeed shows 168. The functionality is working perfectly as intended.

Now, I want to take it a step further and make "Total: $" a variable so that I can easily adjust it for modularity.

In order to achieve this, I initialized:

 var stringToSearch = 'Total: $';

and then altered the code like this:

 totalCost = totalCost.match(/[^stringToSearch]*$/);

Upon logging the results:

 console.log(totalCost+" || "+stringToSearch );

The output is:

$168 || Total: $

I'm puzzled as to why introducing this variable has caused such unexpected behavior?

Answer №1

It amazes me that your regular expression actually found "120" by pure chance!

The pattern [^Total: $]*$ instructs the regex engine to search for everything except the characters 'T', 'o', 't', 'a', 'l', ' ', or '$' as many times as possible until the end of the line ('$' is not interpreted as a literal dollar sign in this context). What got matched? Only the numbers '1', '2', and '0' that didn't fall within the specified character set.

Your goal was to extract the number following the string 'Total: $':

var totalCost = 'Total: $168',
    matches = totalCost.match(/^Total: \$([\d\.]*)/),
    totalCostNum = matches ? parseFloat(matches[1]) : 0;

To achieve this, you must first escape your target string so it can be literally matched, then construct your regex using new RegExp:

var totalCost = 'Total: $168',
    stringToMatch = 'Total: $',
    escapedString = stringToMatch.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'),
    regexForString = new RegExp(escapedString + /([\d\.]*)/.source),
    matches = totalCost.match(regexForString),
    totalCostNum = matches ? parseFloat(matches[1]) : 0;

Answer №2

Seems like incorporating a variable into a JavaScript regex can be tricky as seen here. The example /[^stringToSearch]*$/ is used to match any substring that ends with characters not found in the literal string "stringToSearch". To make it more adaptable, you can utilize the RegExp constructor:

totalCost = totalCost.match(new RegExp("[^" + stringToSearch + "]*$"));

Answer №3

If you're looking to transform your regular expression into a variable that can be applied to various inputs, consider this approach:

let regExp = /^Total: \$(\d+)/;
regExp.exec('Total: $168');
// [ 'Total: $168', '168', index: 0, input: 'Total: $168' ]
regExp.exec('Total: $123');
// [ 'Total: $123', '123', index: 0, input: 'Total: $123' ]

I've made adjustments to the regex in my example due to issues with its functionality not aligning with your expectations.

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

Currently, I am creating a regular expression to manage a specific task, but I have hit a roadblock in

Criteria: The string must not contain any uppercase letters. Special characters such as '^$.?*+()' are not allowed in the string. If the string includes '[', it must be followed by zero or more characters other than '[' and & ...

Encountered an error while trying to download a PDF document in React

I'm currently working on adding a button to my website portfolio that allows users to download my CV when clicked. The functionality works perfectly fine on my localhost, but after deploying it to AWS Amplify, I encountered an error. The error occurs ...

Utilize the jQuery function as a callback argument

There is a jQuery plugin that I am currently working on: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head><title></title> <script type="text/javascript" sr ...

In Google Chrome, the edges of hexagons appear jagged and not smooth

I have encountered an issue in Chrome where I created a hexagon group using HTML and CSS. While it displays fine in Firefox, the edges of the hexagons appear distorted in Chrome. Here are my code snippets: HTML <div class="col-sm-12 margin-left-100" i ...

Iterate through JSON objects

Having an issue with looping through JSON using jQuery AJAX. Despite receiving the JSON data from PHP and converting it to a string, I'm unable to loop through it properly in JavaScript. In my for loop, I need to access $htmlvalue[i] to parse the data ...

Scheduling casperjs on Heroku for automated tasks

Recently, I developed an application using casperjs to extract sports data from a specific website. My goal is to automate this application on heroku by setting up a cronjob to store the sports results in either a CSV file, database, or possibly external ...

Zingchart encounters issues when attempting to plot a CSV file containing over 10 columns

Situation: I want to create a Zingchart graph from a CSV file containing 37 columns. The header in the CSV file will be used as the legend for the graph. Issue: When I define less than 10 elements in the header (including the X-axis name), everything wo ...

Set up a JavaScript function that triggers an alert if two numbers are determined to be equal

I created a code snippet that should display an alert message when a button is clicked, indicating whether two random numbers generated are equal or not. The random numbers must be integers between 1 and 6. I implemented this functionality in JavaScript bu ...

What is the best way to output multiple Div elements using Jquery or Javascript?

I have the following HTML code snippet: <div id="box"> <div id="id_1></div> <div id="id_2></div> <div id="id_3></div> <div id="id_4></div> </div> Can someone guide me on how to use Jquery or ...

Facing an issue with Heroku deployment where a React/Express app is encountering a 'Failed to load resource' error in the console while requesting the chunk.js files

Upon deploying my React application on Heroku, I encountered errors in the console. Refused to apply style from 'https://radiant-tor-66940.herokuapp.com/index.css' because its MIME type ('text/html') is not a supported stylesheet MIME ...

hosting a NextJS development server on the local network

When launching ReactJS with the npm start command, the development server is opened on both localhost:3000 and the network at 192.168.1.2:3000. Testing the app on various devices was a breeze thanks to this setup. Now that I've delved into learning N ...

Using PHP, JavaScript, and Bootstrap to display success or error messages for form fields through AJAX

I am working on a form where users input an 'authorisation code' that is then checked against a database using AJAX and PHP. Currently, the form displays a tick if the code is valid and a cross if it is incorrect. I would like to utilize Bootstra ...

Issues with the Jquery feedback plugin's functionality are currently preventing it

I wanted to incorporate a feedback feature into my web application. To do this, I searched on Google and found a suitable jQuery plugin. I followed the documentation provided by the plugin, including the library in my HTML file, and then wrote the code as ...

Steps for organizing a list based on the number of clicks

I've created an HTML list with images of political party logos. Each logo is a grid item that can be clicked on. I want to sort the list based on the number of clicks each logo receives, essentially ranking them by popularity. However, I'm not su ...

How to efficiently retrieve a form's data from multiple forms with identical ids in JavaScript

I am facing a challenge with multiple forms on the html page that have the same ID. I need to send each form's information to the server based on user selection, but I haven't been able to find a relevant solution. For my Authorization polic ...

Tips for importing an external JavaScript file and accessing its data within a ReactJS project?

Currently, I am working on a React project using create-react-app. My objective is to load an external JavaScript file (hosted in IIS) and utilize the data it contains. To fetch this file, I am including a script in my index.html like so: <script type ...

Is it recommended to run JavaScript functions obtained from REST APIs?

Our single page application is built on Angular 4 and we are able to change input fields based on customer requirements. All the business rules for adjusting these fields are coded in JavaScript, which runs on the Java Platform and delivers the output thro ...

Tips on showing content while filtering is taking longer with AngularJS

When working in Angular, I encountered a situation where filtering a large amount of data in a table was slowing down the process. To address this issue, I wanted to display a spinner every time a filter operation was in progress. Here is an example simil ...

Utilizing the output from a console.log in a webpage

Although the function I created is functioning properly and successfully outputs the value to my terminal onSubmit, I am facing difficulty in understanding why this code isn't updating my html. router.post('/index', function(req, res, next) ...

Attempting to incorporate Google charts into a div using jQuery's load function

Trying to incorporate a basic Google chart using jQuery .load functionality to transfer the chart into another webpage with a specific containing DIV: <html> <head> <script type="text/javascript" src="https://www.google.com/jsapi">< ...