The difficulty is not to insert a space, but to correct the position of the cursor, which only supports ie9+, Chrome browser
Note: This uses the jquery framework
Core code
$ (function () {
$ (' #kahao '). On (' KeyUp ', function (e) {
///only when entering numbers)
if (E.which >= && E.which <=) | |
(E.which >= && E.which <= 105)) {
//Get the position of the current cursor
var caret = This.selectionstart
//Get the current value
var value = This.value
// The number of spaces from the left to the coordinates
var sp = (Value.slice (0, caret). Match (/\s/g) | | []). Length
//Remove all spaces
var nospace = value.replace (/\s/g, ')
//re-insert space
var curval = This.value = Nospace.replace (/(\d{4})/g, "$".
the number of spaces from the left along to the original coordinates
var cursp = (Curval.slice (0, caret). Match (/\s/g ) || []). length
//fixed cursor position
this.selectionend = This.selectionstart = caret + cursp-sp
}
}
)
Full code: already tested
The test was really good, and it used a lot of regular
\s matches any white space character, including spaces, tabs, page breaks, and so on. equivalent to [\f\n\r\t\v].
For a tutorial on regular expressions, refer to this article:
Http://www.jb51.net/tools/zhengze.html
Http://www.jb51.net/tools/regexsc.htm