JS use regex to set input field value

Is there a way to automatically format the input value in an HTML time picker field using regex and the replace function? For example, when a user enters numbers, the input value should be formatted accordingly based on a specific pattern.

I attempted to achieve this using the following code snippet, but it only returns the original string I entered:

console.log(value.replace(/^(([0-9]{1})|([0-1]{1}[0-9]{1})|([2]{1}[0-3]{1}))(([:]{1})?)(([0-5]{1}[0-9]?)?)$/g, ''));

Answer №1

If you are utilizing a user interface framework, it's recommended to consult their documentation as they may have a plugin available for this task. Alternatively, if you prefer to tackle it yourself:

On the HTML side, you can make use of the type="time" attribute (be sure to check for browser support).

In JavaScript, you could implement something like ^([01]\d|2[0-3]):?([0-5]\d)$ on form submission, for example.

const TIME_REGEX = /([01]\d|2[0-3]):?([0-5]\d)$/;

const myTimeElm = document.getElementById('myTime');
const outputElm = document.getElementById('output');

let timer;

outputElm.addEventListener('click', () => {
  if (TIME_REGEX.test(myTimeElm.value)) {
    outputElm.innerText = myTimeElm.value;
  } else {
    outputElm.innerText = "Error!"
  }
});
#output {
  cursor: pointer;
}
<input type="time" id="myTime" value="00:00">

<span id="output">click here!</span>

If the HTML's type="time" isn't suitable, you could consider using a mask for your input to capture the user's input and display the formatted result in a separate component.

Solely relying on RegEx might not deliver the desired user experience, especially when considering the manipulation of the input cursor position.

Alternatively, you can opt for a library that handles this functionality for you (Cleave.js, for instance).

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

Numerous options available in a dropdown menu

I have a Dropdown menu that offers various functions. "Update" option redirects to a page for updating information "Export Form" option redirects to a page for exporting the form Although the current code allows these actions, I am facing an issue with ...

Page flickers when jQuery is used to scroll to an element

One issue I have encountered is with a link that, when clicked, should scroll down to a specific element on the page. However, every time I test this feature, there seems to be an inconsistency where the page may momentarily flash before scrolling as inte ...

Increase the bottom padding or add some extra space to the Bootstrap form or page

I am currently working on enhancing a Bootstrap Form that includes reset/submit buttons positioned at the bottom. A common issue is when iPhone users attempt to click the Submit button, which initially displays Safari icons before requiring an extra tap to ...

Unable to hide the mobile menu button

https://i.sstatic.net/5rdYY.pngI am currently working on a fun website project . I am facing an issue with the mobile menu button not disappearing using display:none in Safari on my iPhone when in landscape mode, even though it works fine in Chrome. My g ...

Modify the value of a variable's color using a combination of bootstrap, JavaScript, and jinja2

I need to show different colors for various Jira statuses such as Open, In Progress, Reopened, Resolved, and Closed. The current solution is functional, but I am searching for a more efficient method. {% set state = 'Closed' %} {% if state ==&ap ...

Show information based on the user's role

I need to adjust my menu so that certain sections are only visible to specific users based on their roles. In my database, I have three roles: user, admin1, and admin2. For instance, how can I ensure that Category 2 is only visible to users with the ROLE_A ...

How disabling SSR is causing my styles to break in Nextjs

My Nextjs app is causing some issues with styling when I disable SSR to connect to Metamask using the window object. Specifically, the Navbar title style changes when SSR is disabled and the dev server is restarted: With SSR enabled: https://i.sstatic.net ...

The impact of Jquery datatable version 1.10 on the dropdown component of Bootstrap version 5.1

On my website, I am utilizing Bootstrap v5.1 and Datatable v1.10 in my project. However, this version of Datatable is causing issues with the Bootstrap dropdown functionality. The dropdown menu is not opening as expected. Strangely, no errors are being gen ...

Creating a Page with Python Selenium for JavaScript Rendering

When using Python Splinter Selenium (Chromedriver) to scrape a webpage, I encountered an issue with parsing a table that was created with JavaScript. Despite attempting to parse it with Beautiful Soup, the table does not appear in the parsed data. I am str ...

Having trouble resetting Material UI Radio Button Group in Formik form within React?

formik.resetForm() is effective in resetting the value, but the Material UI radio button group does not reset correctly: The last selected radio button remains selected. How can I ensure the radio button group is reset properly after submission? import { u ...

Exploring the Challenges of Dynamic Routing in ReactJS

I have a set of components that I need to convert into dynamic URLs. When accessing the browser, for example, http://localhost:3000/houses/1, I want it to display House 1. Everything else in the application is functioning correctly. I just need to resolve ...

Manipulating the zoom level of a webpage through HTML tags or javascript

Is there a way to adjust the zoom level of a webpage using HTML or JavaScript? I am trying to display a webpage on Internet explorer 9 with a zoom property set to 85%. ...

Send the form embedded in an iframe to a separate window

I have a form embedded in an iframe, but I'm looking to open the submitted form in a new window. What would be the best way to achieve this? ...

Iterate through the loop to add data to the table

Looking for a way to append table data stored in local storage, I attempted to use a loop to add cells while changing the numbers based on row counts. Here is my JavaScript code snippet: $(function() { $("#loadTask").change(function() { var ta ...

The AngularJS beginner routing application is malfunctioning and needs fixing

I've been diving into Angular JS but hit a roadblock with a basic angular routing program. I need some guidance on what's going wrong. If you want to check out the complete project code, visit my GitHub repository: https://github.com/ashpratap00 ...

What is the proper way to retrieve multiple property values stored in a property name using getJSON

I'm having trouble getting multiple languages to work in my code. Could someone assist me and provide guidance on how to write multiple choices for the property name language? When I input code like this to display only Dota 2 games in English, every ...

An issue occurred when attempting to retrieve JSON data using an Ajax

After making an ajax call below, I encountered an error that left me puzzled. The variable 'response' in the success function is structured as follows: {"status": "complete", "username": "test", "error": "0", "message": ""} Surprisingly, when I ...

Utilizing HTML/CSS to display text and an image positioned above a sleek navigation bar

I am struggling to align a logo on the left side of my website, with text on the right next to it, all placed above the navigation bar. Despite my efforts, I just can't seem to get them positioned correctly! CSS .headerLogo{ float:left; marg ...

Top methods for incorporating whitespace on both sides of the page

Currently working on a ReactJS/MaterialUI webapp and looking to enhance the layout. Seeking advice on whether it's best practice to add padding or margin to create space on the left and right side of the page, similar to popular websites like Stack Ov ...

Uh-oh! Major issue: CALL_AND_RETRY_LAST Allocation was unsuccessful - system is low on memory

I'm experiencing an issue when trying to download a CSV file. It works fine for 40,000 records but runs into a "process out of memory" error when attempting to download 80,000 records via the API. Can someone please assist with this problem? app.ge ...