[javascript] Replace special characters in a string with _ (underscore)

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: & / \ # , + ( ) $ ~ % .. ' " : * ? < > { }

This question is related to javascript jquery

The answer is


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

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

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

string = string.replace(/[\W_]/g, "_");