Assistance with JavaScript regular expressions for dividing a string into days, hours, and minutes (accounting for plural or singular forms)

My challenge is with handling different variations in a string

var str = "2 Days, 2 Hours 10 Minutes";

When I use :

str.split(/Days/);

The result is:

["2 ", ", 2 Hours 10 Minutes"]

This method seems useful to extract values like "days", "hours" and "minutes" from a string.

However, it gets complicated when the string format changes, for example:

var str = "1 Day, 2 Hours 10 Minutes";

In this case, the string reads "1 Day" instead of "2 Days," altering the placement of "s." Is there a way to split a string based on

Day(s)
Hour(s)
Minute(s)

Answer №1

If you're utilizing a Regular Expression for splitting, simply add a question mark after the 's' to make it optional:

str.split(/Days?/);

To ensure case-insensitivity, include the i flag in the Regex:

str.split(/days?/i);

You can also achieve this in one line using the match string method (instead of split) like so:

("2 Days, 3 hours, 5 minutes").match(/(\d+)\s*days?\,?\s*(\d+)\s*hours?\,?\s*(\d+)\s*minutes?/i)

This will give you an array with values representing days, hours, and minutes respectively.

To explain the Regex in plain terms:

  • (captured group, i.e. array item 1) 1 or more digits
  • zero or more whitespace characters
  • day
  • optional s
  • optional comma
  • zero or more whitespace characters ... and repeat for hours and minutes.

Refer to the documentation on regex matching in strings here, and detailed resources on regular expressions here.

Answer №2

Of course:

str.split(/Days?/);
str.split(/Hours?/);
str.split(/Minutes?/);

Answer №3

If you want to condense the Days/Hours/Minutes into a single 3 element array and are confident that your inputs will always contain a value (even if it is 0), a simpler approach could be to remove all non-numeric and non-space characters, then split the string on spaces and eliminate any empty elements.

var result = new Array();
var tempstr = str.replace(/[^0-9\s]/g, ''); 
var arr = tempstr.split(' ');

for(var i = 0; i<arr.length; i++) {
    if (arr[i]) {
        result.push(arr[i]);
    }
}

Disclaimer: The method for cleaning arrays was sourced from this Stack Overflow post.

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

The operation malfunctions if the variable input is below 50, causing it to produce inaccurate results

The function "calcFinalTotal()" was created to calculate the post-tax discount on a purchase of items that were previously totaled and stored in an input tag with the ID of "totaltaxamount". This function applies a 10% discount to orders between $50 to $ ...

Do we really need to use the eval function in this situation?

Just wondering, is it reasonable to exclude the eval() function from this code? Specifically how <script> ... ... function addGeoJson (geoJsonPath, iconPath = "leaflet-2/images/marker-icon.png", iconSize = [30,50], popUpContent, ...

Attempting to use express and nodemailer to send an email, but there is absolutely no output appearing in either the console or the terminal

When I click the send email button, it should send the data to a mailhog inbox. However, nothing happens - no errors in the console or terminal. My goal is to use nodemailer to send the name, email, chosen plan, and message from the form to the mailhog add ...

Obtain CSS attributes for utilization in Rails variables and database operations

Whenever I click on multiple divs labeled as scale-up, I am able to acquire the css attribute. Yet, my goal is to save these imported css properties in Rails variables and store them in the database. Ultimately, what I aim for is to retrieve the Css prop ...

Execute command problem

Explaining this code may be a bit tricky, but I'll do my best. Below is the code snippet for executing a slash command. client.on('interactionCreate', async interaction => { if (!interaction.isCommand()) return; const command = c ...

Facing compatibility problems with JavaScript and Cascading Style Sheets in Google Chrome?

Welcome to the site . Let's address a couple of issues with JavaScript and CSS: Firstly, the JS code seems to be malfunctioning only in Chrome, throwing an error that reads: 'Uncaught TypeError: Object [object Object] has no method 'on prij ...

How can I remove a row from an MVC webgrid using an ajax call?

Within my MVC Razor view, I have a partial view containing webgrid data. My goal is to include an action link to delete a specific row of data. To accomplish this, I crafted the following JavaScript function: function delMeal(pid) { if (confirm("Do yo ...

The slider customization on Joomla is functioning perfectly on my local machine, but it seems to be encountering some issues on

Having recently started working on a Joomla website for the first time, I encountered some challenges when trying to add a slider module. Despite successfully implementing the slider on my local machine, I faced issues when transferring the code to the liv ...

I need help with customizing the progress bar in HTML and CSS

How can I create a progress bar like the one shown below: .detail-load { height: 42px; border: 1px solid #A2B2C5; padding: 1px; border-radius: 10px; } .detail-load > .detail-loading { background: #904BFF; height ...

Tips to avoid multiple HTTP requests being sent simultaneously

I have a collection of objects that requires triggering asynchronous requests for each object. However, I want to limit the number of simultaneous requests running at once. Additionally, it would be beneficial to have a single point of synchronization afte ...

Transforming vanilla JavaScript into jQuery

Is there a more efficient way to write this code using jQuery? It's functioning properly in Firefox but not in Safari or Chrome without any error messages, making it difficult for me to troubleshoot. Any suggestions or insights would be greatly appre ...

Prevent the hiding of a select element with jQuery Chosen Select

I am facing difficulty hiding a select element with the chosen-select class if it does not have any elements present. I attempted: $("#Category2").hide(); and also tried removing the chosen-select class before hiding the element: $("#Category2").re ...

Switching Out Bootstrap Dropdown with Dropup (Varying functionality on two almost identical implementations)

In the midst of my project on Github Pages, I encountered an interesting issue involving replacing a bootstrap .dropdown with .dropup when the div's overflow-y: scroll causes the dropdown menu to be cut off or overflow. The functionality can be viewed ...

No element found with the specified exportAs value of "ngForm" on the <form> tag

I am currently experimenting with a template driven form in Angular, but I encountered an error stating **There is no directive with “exportAs” set to “ngForm"** I have made sure to import FormsModule and ReactiveFormsModule in app.module.ts as well ...

Querying Mongoose Nested Data in Express: A Comprehensive Guide

I need to retrieve the "stocked" boolean value for item "4" belonging to user "456" from my mongoose data collection. However, when I try to query for this specific information, I end up receiving the entire user object instead. Data: data = [{ use ...

"Enhance your website with powerful AJAX functionality using the October CMS

Can you help me troubleshoot this AJAX error I'm encountering when trying to call an AJAX action? The error message is indicating an 'Invalid handler name.' The correct format for the handler name should be "onEvent" I am attempting to u ...

Javascript regular expressions are not functioning as expected

When testing the string "page-42440233_45778105" against the pattern "(page-\d+_\d+)", an online tester at was able to successfully find a match. However, when executing the code in browser js, the result is null. Why might this be? var re = ne ...

A step-by-step guide on incorporating universal CSRF tokens using JQuery AJAX

As part of my development work, I am in the process of creating jquery code that communicates with the server through ajax to input data into a database based on specific request parameters. My main concern at this point is the vulnerability to CSRF attac ...

Converting string literals to an array of enums

I have a scenario where I am getting the following data in an API response: { "roles": [ "ADMIN", "USER" ] } The response always includes an array of roles (USER, PRESENTER, ORGANIZER, and ADMIN). I am looking to transform this into a valid TypeScript a ...

creating reactive images with Vue

The original code utilized an image in a menu as shown below: <img :alt="$t('more')" class="mobile-plus-content visible-xs" src="../../../assets/img/plus79.png" /> This results in: src="data:image/png;base64,the image" I made a mo ...