How can I verify in Javascript that a string contains at least one set of letters and numbers using regex?

I am currently trying to decipher the appropriate regex for identifying a pattern similar to 2d1h30m10s, accepting any valid variation such as 1h, 1h30m, 30m, 10s, or any combination of these. Could regex be the right solution in this scenario?

I have been attempting to comprehend it, yet despite my efforts, all I receive is false when running various tests:

/^(0?[1-9]|1[0-2][h])([1-6][0-9][m])([1-6][0-9][s])\d$/.test('2d1h10m10s')
/^(0?[1-9]|1[0-2][h])([1-6][0-9][m])([1-6][0-9][s])\d$/.test('10m10s')
/^(0?[1-9]|1[0-2][h])([1-6][0-9][m])([1-6][0-9][s])\d$/.test('10s')

What elements am I overlooking here?

Answer №1

To make each section of the regular expression optional, you should exclude that unit.

Remove [h] from one of the alternatives to match both 12h and 01h.

Avoid using \d at the end.

The pattern does not account for single-digit minutes or seconds. Additionally, there is no need for 60s or 60m as they can be represented as 1m and 1h respectively.

/^((0?[1-9]|1[0-2])h)?([1-5]?[0-9]m)?([1-5]?[0-9]s)?$/

DEMO

It is unnecessary to enclose h, m, and s in square brackets since they are single characters.

Note that with each unit being optional, the pattern will also match an empty string. It's recommended to validate this separately from the regular expression.

Answer №2

Perhaps this will be the solution

\d+\w+

If my comprehension is accurate, you are attempting to verify if a string includes characters that come after numbers.

Answer №4

Here is the correct format for the expression you are trying to use:

/^((0?[1-9]|1[0-2])h)?((([0-5]?[0-9])|60)m)?((([0-5]?[0-9])|60)s)?$/

The original expression you had provided has a couple of issues: 1. the use of \d at the end, and 2. the capturing scope (extra parentheses in my corrected expression).

With this new expression, it will also be able to capture formats like 1h13s.

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

NodeJS introduces the nullish coalescing assignment operator (??=) for effective nullish value handling

Is it possible to use the Nullish coalescing assignment operator (??=) in NodeJS? const setValue = (object, path, value) => { const indices = { first: 0, second: 1 }, keys = path.replace(new RegExp(Object.keys(indices).join('| ...

I am encountering an issue where I am sending an AJAX request to a PHP file with the datatype set as JSONP, but I

When I click on the submit button, I am sending a variable to sendmail.php. However, PHP is showing that 'contactname' is undefined. Why is this happening? Here is the code snippet: var name = document.getElementById('stream_cotactname&apo ...

Utilize vue.js input field to search for a specific username within a constantly updating list of users

I have created an input search functionality to filter a list of users using PHP. Now, I am attempting to implement the same filtering feature in Vue.js so that when a user searches for a name, the filtered user will be displayed in the list. Below is the ...

converting nested object structures in typescript

I'm trying to flatten a nested object in my Loopback and Typescript controller Here's the structure of my model : export class SampleModel { id: number; code: number; guide?: string; gradeData?: string; } Take a look at this example obj ...

Testing Your Angular 7 Code: Unit Testing Made Easy

I am currently working on developing unit tests for this angular script: export class DataService { private csrfToken: string = ''; private isContentShown: BehaviorSubject<boolean> = new BehaviorSubject(true); constructor(private h ...

The Ionic application encounters an issue with the $stateParams being

Can someone assist me with resolving an issue related to ionic $stateParams? Here is the state configuration: .state('tabs.categories', { url: "/categories/:parentID", views: { 'categories-tab': { templateU ...

The React hook is activated each time a key is pressed, but it should ideally only be triggered when there is

I have created a hook for my Formik form that should be called whenever a specific field's Selection option is chosen. However, I am facing an issue where the hook is being triggered on every key press in every form field. I am not sure what mistake ...

The issue with Rails and Ajax request failing to load arises when including a .js.erb file

I have a project in mind for a simple website, akin to a stock tracker. One of the key features I'm trying to implement is using ajax to get results without having to reload the entire page. Although I am able to retrieve the HTML with the desired dat ...

Issue encountered while attempting to load several google charts simultaneously

What do I need? I am in need of two Google charts, one on each tab of the website as shown in the screenshot below: Tabs What seems to be the issue? The second chart is not loading properly and showing mixed information. This can be observed in the scre ...

I am looking to efficiently store various pieces of data in a database by utilizing a singular variable through JS, PHP, and AJAX for streamlined processing and management

I am not very familiar with the technical jargon in programming, so please bear with me if my question is a bit unclear. To provide more clarity, I have shared the code that I have already written. I will elaborate on the issue after presenting the code: ...

Choose your options effortlessly with CSS or JavaScript dropdown menus

As a novice web developer, I am contemplating whether dropdown menus are more suitable to be coded in CSS or JavaScript. What are the advantages and disadvantages of each approach? ...

Regular Expression: Multiple capturing entities

Looking to extract data from a table in an ASCII text file? Take a peek at this snippet: QSMDRYCELL 11.00 11.10 11.00 11.00 -.90 11 11000 1.212 RECKITTBEN 192.50 209.00 192.50 201.80 5.21 34 2850 5.707 RUPALIIN ...

How can I adjust the column width in OfficeGen?

Currently, I am utilizing officeGen for the purpose of generating word documents. <sup> let table = [ [ { val: "TT", fontFamily: "Times New Roman", }, { val: "Ten hang", ...

Locate the parent element that has the smallest amount of space taken up by its child elements

My goal is to determine which container, among several <divs>, each containing multiple child <divs> of varying sizes, has the smallest amount of space covered by the child elements. <div class="container" id="first"> ...

Using the ref callback to access getBoundingClientRect values in React Components

I'm having some trouble extracting data using the getBoundingClientRect() method from a set of animated div elements. The issue I'm facing is that the refCallback function is returning empty DOMRect objects. If you're interested, feel free t ...

Is it possible to trigger an event each time an Ajax request is made within AngularJS?

I am looking for a way to automatically display a spinner with a dark overlay every time a call is made to the backend. While I know I can manually implement this by triggering the spinner before each call, I prefer a solution that does not require addit ...

Configuring React classes for compilation within Play

After incorporating a basic React class into my Play project at /app/assets/js: var Question = React.createClass({ render: function() { return (<div> <p>{this.props.content}</p> <br> <p>{this.props.an ...

Tips for reloading a page when using the back button on MAC Safari

On my ASP.NET MVC application, I have two pages (A and B) with checkboxes and textboxes on page A. After moving from page B to page A using the browser back button in Safari on MAC, the page does not refresh and retains the old values for checkboxes and t ...

Dealing with mistakes in a contact form - Finding the correct function

I developed a form using material-ui in React. I am facing some issues with my submit function. I am using a snackbar to notify the user about the successful submission, as well as a snackbar to alert them about missing required fields. The problem arise ...

Error: Google Chrome encountered an unexpected token } that caused a syntax error

I encountered an error that reads: Uncaught SyntaxError: Unexpected token } This error only appears in Chrome, while other browsers like Mozilla and IE do not show it. Here is my script causing the issue: <script type="text/javascript" language="jav ...