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.
Use the String. replaceAll method to replace all spaces with underscores in a JavaScript string, e.g. string. replaceAll(' ', '_') . The replaceAll method returns a new string with all whitespace characters replaced by underscores.
If you are having a string with special characters and want's to remove/replace them then you can use regex for that. Use this code: Regex. Replace(your String, @"[^0-9a-zA-Z]+", "")
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With