Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to replace colon or dash with empty string if there are 2 characters before them

I need a regex to replace strings like this:

aa:bb:c:  //to be aabbc:
or 
aa-bb-c-  //to be aabbc-

I can do this by this code
text.replace(/.{2}[:-]/g, (match) => match.substring(0,2));

I am asking if this could be done by regex only without using replacer function like
text.replace(regex, "");

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can replace with regex capture group using (), which $1 means the first match group

text.replace(/(.{2})[:-]/g, "$1")

Refrence:
https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/RegExp#using_a_regular_expression_to_change_data_format

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading