Home > Blockchain >  Remove `-` character at the end of domain name
Remove `-` character at the end of domain name

Time:11-15

I have this code:

string.replace(/[~!@#$%^&*()_\- ={}[\]|"':;?,/><,\\]/g,'');

I want to remove all invalid characters from domain. It's working fine, but additionally I want to remove - character from the end if it is here.

So, te-!#$#@$@#st-.com will be te-st.com.

I tried added something like that [-]$, so the code looks like this:

string.replace(/[~!@#$%^&`*()_\ ={}[\]|"':;?,/><,\\][-]$/g,'')

But this doesn't work, any ideas?

CodePudding user response:

You should use an alternation here:

string.replace(/[~!@#$%^&`*()_\ ={}[\]|"':;?,\/><,\\]|- (?=\.)/g, '')

Demo

This regex pattern says to match:

  • [~!@#$%^&*()_\ ={}[\]|"':;?,\/><,\\] match a symbol
  • | OR
  • - (?=\.) match 1 or more dashes which are followed by dot (but do not consume the dot)

CodePudding user response:

Maybe use replacer function:

const firstIndex = string.indexOf('-');
string.replace(/[~!@#$%^&*()_\- ={}[\]|"':;?,/><,\\]/g,
    (match,offset) => offset === firstIndex ? match : ''
);
  • Related