Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 708
Rafael Avatar asked Aug 15 '17 18:08

Rafael


People also ask

How do you replace a section of a string in regex?

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.

Can I use regex in replace?

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.

Is regex faster than string replace?

String operations will always be faster than regular expression operations.

What is $1 in regex replace?

For example, the replacement pattern $1 indicates that the matched substring is to be replaced by the first captured group.


1 Answers

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');
like image 141
marvel308 Avatar answered Oct 05 '22 18:10

marvel308