Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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.

like image 678
Do Good Avatar asked Oct 22 '12 21:10

Do Good


People also ask

How do I replace a space underscore?

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.

How do you replace special characters in regex?

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]+", "")


1 Answers

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

like image 111
epascarello Avatar answered Sep 17 '22 14:09

epascarello