我的数字代码长度从6-11位变化
在每3位数之后用连字符分隔
可能的组合
123-456
123-456-78
123-456-7890
所以,在这里,我试图将用户输入的代码转换为这种格式,即使在中间输入空格和连字符也是如此。
对于Ex:
123 456-7 -> 123-456-7
123456 789 -> 123-456-789
123456 -> 123-456
有效的用户输入格式是3digits [空格或连字符] 3digits [空格或连字符] 0to5digits
我试过这样的
code.replace(/^(\d{3})[- ]?(\d{3})[- ]?(\d{0,5})$/,'$1-$2-$3');
但是当只有6位数字时,在数字的末尾有一个连字符( - ),这是不希望的。
123-456-
有人可以帮我这个吗?谢谢。
答案 0 :(得分:2)
The easiest way is probably to just do this with a second replace
:
code.replace(/^(\d{3})[- ]?(\d{3})[- ]?(\d{0,4})$/,'$1-$2-$3')
.replace(/-$/, '');
This is chaining a second replace function, which says "replace a -
at the end of the string with an empty string". Or in other words, "if the last character of the string is -
then delete it.
I find this approach more intuitive than trying to fit this logic all into a replace
command, but this is also possible:
code.replace(
/^(\d{3})[- ]?(\d{3})[- ]?(\d{0,4})$/,
'$1-$2' + ($3 == null ? '' : '-') + $3
)
I think it's less obvious at a glance what this code i doing, but the net result is the same. If there was no $3
matched (i.e. your sting only contained 6 digits), then do not include the final -
in the replacement.
答案 1 :(得分:1)
I believe this will do it for you - replace
^(\d{3})[ -]?()|(\d{3})[ -]?(\d{1,5})
with
$1$3-$2$4
It has two alternations.
^(\d{3})[ -]?()
matches start of line and then captures the first group of three digits ($1), then optionally followed by a space or an hyphen. Finally it captures an empty group ($2).(\d{3})[ -]?(\d{1,5})
matches, and captures ($3), three digits, optionally followed by a space or an hyphen. Then it matches and captures (($4)) the remaining 1-5 digits if they're present.Since the global flag is set it will make one or two iterations for each sequence of digits. The first will match the first alternation, capturing the first three digits into group 1. Group 2 will be empty.
For the second iteration the first match have matched the first three digits, so this time the second alternation will match and capture the next three digits into group 3 and then the remaining into group 4.
Note! If there only are three digits left after the first match, none of the alternations will match, leaving the last three digits as is.
So at the first iteration group 1 are digits 123. group 2, 3 and 4 are empty. The second iteration group 1 and two are empty, group 3 are the digits 456 and group 4 are digit 7-11.
This gives the first replace $1 = 123-
plus nothing, and the second 456-67...
.
There's no syntax checking in this though. It assumes the digits has been entered as you stated they would.