Good morning, I'm trying to generate a regular expression to treat a string as a string, what I want is to put :
after every 2 numbers, I know I could do it with a substring
but I would like to do it with the regular expression.
var str = "013012";
console.log(str.replace(/\B(?=(\d{2}))/g, ":"));
console.log('String esperado 01:30:12')
// String Obtenido 0:1:3:0:12
// String esperado 01:30:12
I hope you can help me
Thanks.
You can use the following function:
I added a regex to add
:
every 2 characters and another expression where the one found at the end of the string is removed.I hope it is helpful. Greetings.
this can help you:
In the first method: Using the dollar sign ($) represents the block that matches the expression in parentheses. That's why I separated $1:$2:$3 into 3 groups so that you have the desired format.
In the second method: If we don't know the number of digits. we can replace every 2 digits and add the colon ":" then we recover it with the dollar symbol ($) and since it is the only (first) value we put the number 1. It is because of that that $1 is seen. Because when finding 2 digits it will concatenate the 2 points. Finally, since you would have 2 points left over at the end, we make a replacement that eliminates the last match. That's why you see the dollar sign ($) without a number next to it. Cheers!