Str.replace() replaces an extra character when using regExp

Hi everyone, I’m trying to do something similar to Glitch’s project naming, where all special characters are replaced with dashes. I’m attempting to use regExp, but for some reason it seems to ignore the last character. What I mean by this is if I type in Hello! it will stay the same. If I then type in an extra letter to make Hello!x it will become Hello. Doing this without regExp, e.g.

string.replace(" ", "-")

works fine.
Here’s the code I’m using:

string = string.replace(/[^qwertyuioplkjhgfdsazxcvbnm-][^0-9]/ig, "-");

Obviously string is defined.

Any help would be greatly appreciated!

I recommend putting the regex into , setting test strings, and reading the explanations at the bottom.

Hint: you can put more than one range in a negated set.


Thanks so much! I put them all in one negated set and it worked :smile:
May I ask why it was doing what it was doing?

The two negated sets next to each other means “one character not in set a-z nor minus” followed by “one character not in range 0-9”. i.e. !x is a match.

Well done! :slight_smile:

1 Like

Ah ok, thanks!