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 remove specific character except for the first one using regex in JavaScript?

So, I have a string something like, asd.asd.asd.234432$$..asd888. Now I want to get a string like, .234432888. So what I want to achieve is to remove every dots except for the first one and remove every non number character.

So far I tried *string*.replace(/[^\d.]/gi, new String()). But, it does not work as expected.

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 :

Do a global regex match of characters:

  • (?<!\..*) – find . that doesn’t have . before it at any distance (.*) using a lookbehind negative assertion. That would be the first . encountered.
  • \d+ – find all numbers
  • join the found characters:
const str = 'asd.asd.asd.234432$$..asd888';

console.log(str.match(/(?<!\..*)\.|\d+/g).join(''));
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