Reputation: 1487
I want to use regex to format a number inside an input as I type it.
My problem is: Since I'm using groups to format the number, it only formats when the string matches the regex.
Here's an example:
The full number is: 12312312312
| Formatted would look like: 123.123.123-12
.
If I type 1231231
for example, it doesn't formats to 123.123.1
as I was expecting, only if I type the entire number.
This is my function:
format(value){
// This function returns the formatted string on user input
return value.replace(/(\d{3})(\d{3})(\d{3})(\d+)/, "\$1.\$2.\$3-\$4");
}
Is there any way to make the remaining groups optionals?
Upvotes: 8
Views: 36193
Reputation: 785266
You can use this format
function with 2 calls to .replace
:
Code:
function format(value) {
// This function returns the formatted string on user input
return value.replace(/(\d{3})/g, '$1.')
.replace(/((?:\d{3}\.){2}\d{3})\./, '$1-');
}
console.log(format('1231231')); //=> 123.123.1
console.log(format('12312312312')); //=> 123.123.123-12
Upvotes: 1
Reputation: 10458
You can do it using
function formatStr(str){
str = str.replace(/(\d{1,3})(\d{0,3})(\d{0,3})(\d{0,2})/g, function(a, b, c, d, e){
let ret = "";
if(b != "")
ret = b;
if(c != "")
ret = ret+"." + c;
if(d != "")
ret = ret+"." + d;
if(e != "")
ret = ret+"-" + e;
return ret;
})
console.log(str);
}
formatStr('12312312312');
formatStr('1231231');
Upvotes: 12