Single-line JS implements the input rules of the mobile terminal's money format, js money
Money format testing is a common requirement. I remember that when I first encountered this requirement at work, I did not quite write regular expressions and found a similar solution, the regular expression document is changed to the desired form.
However, the user's input operations are arbitrary, but the prompt information is displayed. Although this method can meet the requirements, it is unfriendly.
In fact, many mobile applications block incorrect input when entering money. They can only enter the correct format. First, let's take a look at the input rules of the money format:
1. Do not enter blank characters or letters
2. Only numbers and decimal places can be entered.
3. the first digit cannot be a decimal point
4. the decimal point can only appear once
5. There are only two digits after the decimal point
6. You cannot enter multiple digits with the first digit being 0.
A seemingly simple question can be considered very well. However, the code can be easily written, and I have spent a lot of time exploring it. Only one row is required for validation.
Function moneyFormat (str) {return str. replace (/[^ \ d \.] | ^ \. /g ,''). replace (/\. {2}/g ,'. '). replace (/^ ([1-9] \ d * | 0 )(\. \ d {1, 2 })(\. | \ d {1 })? $/, '$1 $ 2'). replace (/^ 0 \ d {1}/g, '0 ');}
It's not too early. Let's write so much, and finally paste the Demo I wrote in CodePen, hoping to help people who need it.
The above section describes how to use single-line JS to implement the input rules for mobile terminal money formats. I hope it will be helpful to you. If you have any questions, please leave a message for me, the editor will reply to you in a timely manner. Thank you very much for your support for the help House website!