Remove special symbols and extra spaces and replace with underscore using the replace method

javascript

Solution

Your regular expression `[^a-zA-Z0-9]\s/g` says match any character that is not a number or letter followed by a space.

Remove the \s and you should get what you are after if you want a _ for every special character.

var newString = str.replace(/[^A-Z0-9]/ig, "_");

That will result in `hello_world___hello_universe`

If you want it to be single underscores use a + to match multiple

var newString = str.replace(/[^A-Z0-9]+/ig, "_");

That will result in `hello_world_hello_universe`

Problem

I want to remove all special characters and spaces from a string and replace with an underscore. The string is ``` var str = "hello world & hello universe"; ``` I have this now which replaces only spaces: ``` str.replace(/\s/g, "_"); ``` The result I get is `hello_world_&_hello_universe`, but I would like to remove the special symbols as well. I tried this `str.replace(/[^a-zA-Z0-9]\s/g, "_")` but this does not help.

Original source