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:

| Formatted would look like:

If I type
for example, it doesn't formats to
as I was expecting, only if I type the entire number.

This is my function:

// 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;


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