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.
Your regular expression
[^a-zA-Z0-9]\s/gsays 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.
That will result in
hello_world___hello_universeIf you want it to be single underscores use a + to match multiple
That will result in
hello_world_hello_universe