The implementation code of the bank card number automatically inserts the space every 4 bits based on the jquery implementation _jquery

Source: Internet
Author: User

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

<! 
  DOCTYPE html>  

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.