Home > Software engineering >  Remove invalid characters from domain
Remove invalid characters from domain

Time:11-14

I have this regular expression:

/^(((?!\-))(xn\-\-)?[a-z0-9\-_]{0,61}[a-z0-9]{1,1}\.)*(xn\-\-)?([a-z0-9\-]{1,61}|[a-z0-9\-]{1,30})\.[a-z]{2,}$/

and this domain value: domain!@#$test:ing.com

I want to remove all this unsupported characters, and I tried this:

string.replace(/^(((?!\-))(xn\-\-)?[a-z0-9\-_]{0,61}[a-z0-9]{1,1}\.)*(xn\-\-)?([a-z0-9\-]{1,61}|[a-z0-9\-]{1,30})\.[a-z]{2,}$/,'');

But this doesn't work, any ideas why?

I tried different codes, and I expect that this code will remove unsupported characters from string.

CodePudding user response:

The regular expression in your question is meant to validate domain names. You can cannot use it to replace characters inside a string. You'll have to create a new regular expression with the undesired characters.

Based on your regex, it will probably be something like:

string.replace(/[^a-z0-9\-_\.]/g, "")

^ negates what's inside the brackets...

  • Related