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?
The \[[^\]]*]\[ matches [ , then any 0+ chars other than ] and then ][ . The (...) forms a capturing group #1, it will remember the value that you will be able to get into the replacement with $1 backreference. [^\]]* matches 0+ chars other than ] and this will be replaced.
How to use RegEx with . replace in JavaScript. To use RegEx, the first argument of replace will be replaced with regex syntax, for example /regex/ . This syntax serves as a pattern where any parts of the string that match it will be replaced with the new substring.
String operations will always be faster than regular expression operations.
For example, the replacement pattern $1 indicates that the matched substring is to be replaced by the first captured group.
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With