Rafael Rafael -3 years ago 293
TypeScript Question

TypeScript string replace with regex, groups and partial string

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?

Answer Source

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');

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download