


Implementation code based on jquery to automatically insert spaces into every 4 digits of bank card numbers
难点不是插入空格,而是修正光标的位置,这个只支持IE9+、chrome浏览器
注意:这个使用了jquery框架
核心代码
$(function() { $('#kahao').on('keyup', function(e) { //只对输入数字时进行处理 if((e.which >= 48 && e.which <= 57) || (e.which >= 96 && e.which <= 105 )){ //获取当前光标的位置 var caret = this.selectionStart //获取当前的value var value = this.value //从左边沿到坐标之间的空格数 var sp = (value.slice(0, caret).match(/\s/g) || []).length //去掉所有空格 var nospace = value.replace(/\s/g, '') //重新插入空格 var curVal = this.value = nospace.replace(/(\d{4})/g, "$1 ").trim() //从左边沿到原坐标之间的空格数 var curSp = (curVal.slice(0, caret).match(/\s/g) || []).length //修正光标位置 this.selectionEnd = this.selectionStart = caret + curSp - sp } }) })
完整代码:已经测试
银行卡号4位空格 <script> $(function() { $(&#39;#kahao&#39;).on(&#39;keyup&#39;, function(e) { //只对输入数字时进行处理 if((e.which >= 48 && e.which <= 57) || (e.which >= 96 && e.which <= 105 )){ //获取当前光标的位置 var caret = this.selectionStart //获取当前的value var value = this.value //从左边沿到坐标之间的空格数 var sp = (value.slice(0, caret).match(/\s/g) || []).length //去掉所有空格 var nospace = value.replace(/\s/g, &#39;&#39;) //重新插入空格 var curVal = this.value = nospace.replace(/(\d{4})/g, "$1 ").trim() //从左边沿到原坐标之间的空格数 var curSp = (curVal.slice(0, caret).match(/\s/g) || []).length //修正光标位置 this.selectionEnd = this.selectionStart = caret + curSp - sp } }) }) </script>
经过测试确实很好用,里面用到了很多的正则
\s 匹配任何空白字符,包括空格、制表符、换页符等等。等价于[ \f\n\r\t\v]。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Dreamweaver CS6
Visual web development tools

SublimeText3 Chinese version
Chinese version, very easy to use

Notepad++7.3.1
Easy-to-use and free code editor

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.
