Rafael
Rafael

Reputation: 1487

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?

Upvotes: 8

Views: 36193

Answers (2)

anubhava
anubhava

Reputation: 785266

You can use this format function with 2 calls to .replace:

  1. First we insert a dot after every 3 digits
  2. Second we replace 3rd dot with hyphen

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

marvel308
marvel308

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

Related Questions