简体   繁体   中英

Is there any way to detect and change the input value format?

I am checking and validating the text area value with a regex and I want to change the formating like this: user input:

123456

change to:

12/34/56

can this be done in pure js?

edit:

this is what I did yet:

 function changeIt() {
  var inputChanger = document.getElementById("id").value.replace(something , something);
  document.getElementById("id").value = inputChanger;
}

but no idea how to proceed

Try something like this:

Note: for this code to work, the HTML must come before the JavaScript, but stack overflow apparently re-order's code snippets to always show the JS first (?)

 var input = document.getElementById('my-input'); function format() { // \\d matches a digit, // parenthesis let you use the matched values as $n in the replacement string input.value = input.value.replace(/(\\d\\d)(\\d\\d)(\\d\\d)/, '$1/$2/$3'); } // you probably only need one of these, but it doesn't hurt to have both input.addEventListener('change', format); input.addEventListener('keyup', format); 
 <input type="text" id="my-input" /> 

It can also, of course, be done with some jQuery and maybe a plugin like http://jquery-plugins.net/maskjs-jquery-plugin-to-mask-inputs - but I think it's good to understand what's happening under the hood even if you end up going that way.

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