简体   繁体   中英

JS set input value by regex

I have simple input on my html and i want to when user putting text value in the input value was automatically set by my regex pattern Example: I have time picker input在此处输入图像描述 and I want the user when he enters numbers, the value is automatically formatted in the input. How to do it with regex and replace function?

I tried to do it this way, but in the end I just get the string that I enter.

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, ''));

If you are using a UI framework, refer to their documentation they would probably have a plugin to do it for you. Or if you want to do it on your own:

From the HTML side you can use type="time" attribute (please check the browser support for this ).

And from JavaScript you can use 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 you don't want to use HTML's type="time", consider using a mask for your input where you record the user's input and render the formatted output in a different component.

Since using the RegEx alone won't achieve the same user experience as you may want to workout the input's cursor position.

Or simple use a library that does that for you ( Cleave.js for example)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM