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

Tips for accessing private variables

After running this code in nodejs, I noticed that the 'Count' becomes negative for large values of 'count'. It made me wonder, is it the fault of 'count' or 'chain'? What would be the best approach to modify the &apo ...

Implementing a method to allocate rewards to individual players within a game Bank using arrays in Node.js and JavaScript

In my interactive game, players can choose between two sides to place their bets. At the end of the game, there will be one side declared as the winner and those who placed winning bets will receive a portion of what they wagered. However, I am facing an i ...

Handling Errors in Asynchronous Functions with JavaScriptLet's explore the best practices for

I am a beginner in javascript and recently delved into async/await. After going through various resources, I gained a basic understanding. However, while experimenting with some code examples, I encountered unexpected results which left me puzzled about wh ...

Is there a way to dynamically integrate the Insert Column feature into the ContextMenu of a Syncfusion Treegrid?

What is the best way to add Insert Column functionality to the ContextMenu of a Syncfusion Treegrid? Insert Column Rename Column Delete Column ...

Angular2 - HTML not displaying the response

I am currently mastering angularjs2. In my latest project, I attempted to fetch data from an API and received a response successfully. However, I encountered an issue where the response is not rendering in homepage.component.html as expected. I am unsure o ...

Using Javascript to parse a regular expression in a string

I am facing a challenge with a JavaScript string that contains contact information that needs to be filtered. For example, I want to mask any email or phone number in the message. I have attempted the following approach: function(filterMessage) { ...

Implementing AJAX in Rails for the new/create action can greatly enhance the user

I have a timeline with event sections on it that allow you to create, view, update, and delete events directly on the timeline page. Currently, the functionality for deleting an event is working smoothly as the delete section refreshes along with the timel ...

Sending image to the server with the help of JavaScript

Curious if there is a method to upload an image to the server using javascript or jQuery and then save the image path/name into a database. I am working on a Windows platform server in asp.net 1.1, revamping a web page that is 10 years old. Unfortunately, ...

Forward ReactJS

https://i.stack.imgur.com/r0IAE.pngI'm having trouble implementing a redirect to a submit confirmation page after pressing the submit button on my form. The backend server is set up to send an email upon submission, but adding an href to the button pr ...

Adding space around a label in a React component with TypeScript

Here is the code snippet I am working with: const ParentComponent = () => { const name = "name1"; const type = "type1"; const label = `${name} ${type}`; //something to be done here to add some space // before the text return ( ...

What limitations prevent me from using "await .getAttribute()" in Protractor, despite the fact that it does return a promise?

I have been working on transitioning my Protractor tests from using the selenium control flow to async/await. However, I am facing an issue where it is not allowing me to use await for the .getAttribute() function. Each time I try, I receive the error mess ...

transferring a document using axios, bypassing the FormData interface

One way to upload a file to the server is by using axios along with the FormData api. Here's an example: persist(photo){ let data = new FormData(); data.append('photo', photo); axios.post(`/api/photos/${this.user ...

React Native ScrollView with a custom footer that adjusts its size based on the content inside (

I've implemented the code below to ensure that the blue area in image 1 remains non-scrollable when there is sufficient space, but becomes scrollable when space is limited. However, I'm facing an issue where the ScrollView component is adding ext ...

Jenkins encountered an issue where script execution was blocked on <URL> due to the document's frame being sandboxed without the 'allow-scripts' permission set

When using an iFrame in HTML, it's always best to remember to sandbox it and set the 'allow-scripts' permission to true. However, I'm facing an issue in my pure Angular JS application where there is no iFrame present. It runs smoothly ...

Obtaining the text content of a <div> element when clicked using Selenium

I am trying to extract the email address from the code snippet below, but I am unsure of how to do it. Any assistance would be greatly appreciated! <div class="taLnk hvrIE6 fl" onclick="ta.trackEventOnPage('Listing', 'Email', 774169 ...

The dropdown menu button stubbornly remains open and refuses to close

Having an issue with a dropdown menu button where it should open when clicked on the icon and close when clicking off the icon or on the icon again, but instead, it remains open. Here is a screenshot for reference: https://i.stack.imgur.com/UX328.jpg I&a ...

Exploring the main directive flow, attaining access to `ctrl.$modelView` in AngularJS is

Four Methods Explained: What Works and What Doesn't I recently created an angular js directive where I encountered difficulty accessing the ctrl.$modelValue in the main flow. In my quest to find a solution, I came up with four potential methods, eac ...

Achieving different results by modifying an array within a forEach loop

I am currently working on a forEach() function that increments an array by one for each iteration. The problem I am facing is that whenever I try to display the value of the number variable in the browser's console, it only shows me the final state i ...

The $scope object in Angular is supposed to display the $scope.data, but for some reason, when I attempt to access it

Having an issue with my controller that fetches data from a service. After receiving the data in the controller, I'm using $scope to pass it to the view. Strange behavior - console.logs inside the 'then' function display the data correctly ...

testing express router with several different handlers

I have been testing my guard middleware and everything appears to be functioning correctly, but my expect statement is failing. /// auth.test.js const request = require('supertest'); const express = require('express'); const app = req ...