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

Remove all special consecutive characters

Hopefully a simple one but I can’t find any exact thread on SO for this particular instance:

If I have a string with multiple special characters in a row i.e 'this-is--a---string' I want to remove all duplicate non alphanumeric characters with regex so it would end up as 'this-is-a-string'

The closest i’ve found is .replace(/(.)\1+/g, '$1') but this removes duplicate letters rather than just special characters.

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

On a side note if anyone knows how to remove any non alphanumeric characters from the end of a string with regex then that would be really useful too!

Thanks in advance!

>Solution :

Since you want to collapse only repeated non alphanumeric characters, it should be enough to change your regex replacing the . character class with something that will negate the alphanumeric group [^a-zA-Z0-9].

subject = "a---------------bbbbbb6times_______@@@@@@";

var myregexp = /([^a-zA-Z0-9])\1+/mg;
result = subject.replace(myregexp, "$1");

console.log(result);
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