Skip to content
Advertisement

How to exclude a character from regular expression?

I want to replace all non words characters from a string but I need to check if the word has a hyphen in it but the replace will delete the hyphen . is there a way to do that after I replace everything that is not a letter or do I have to check before replacing ?

this is my code

JavaScript

Advertisement

Answer

Use the regex, [^w-] which means NOT(a word character or -).

JavaScript

Output:

JavaScript

Note that a word character (i.e. w) includes A-Za-z0-9_. If you want your regex to restrict only up to alphabets and hyphen, you should use [^A-Za-z-]

JavaScript

Output:

JavaScript
Advertisement