I want to remove special characters from a string and replace them with the _ character.

For example:

string = "img_realtime_tr~ading3$" 

The resulting string should look like "img_realtime_tr_ading3_";

I need to replace those characters: & / \ # , + ( ) $ ~ % .. ' " : * ? < > { }

4

2 Answers

string = string.replace(/[&\/\\#,+()$~%.'":*?<>{}]/g,'_'); 

Alternatively, to change all characters except numbers and letters, try:

string = string.replace(/[^a-zA-Z0-9]/g,'_'); 
8
string = string.replace(/[\W_]/g, "_"); 

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy