Replace TypeScript string with regular expression, groups, and partial string

I want to use a regular expression to format a number inside an input when I type it.
My problem: since I use groups to format a number, it is formatted only when the string matches the regular expression. Here is an example:
Full number: 12312312312| Formatted format is as follows: 123.123.123-12.

If I type 1231231, for example, it does not format 123.123.1, as I expected, 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 a way to make other groups options?

+4
source share
2 answers

,

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');
Hide result
+8

format .replace:

  • -,

:

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
Hide result
0

Source: https://habr.com/ru/post/1683769/


All Articles