Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
182
rated 0 times [  185] [ 3]  / answers: 1 / hits: 154369  / 12 Years ago, mon, october 22, 2012, 12:00:00

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.


More From » javascript

 Answers
13

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


[#82410] Monday, October 22, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
melindab

Total Points: 511
Total Questions: 109
Total Answers: 106

Location: San Marino
Member since Thu, Jun 25, 2020
4 Years ago
;