Replace special characters in a string with _ (underscore)
JavascriptJqueryJavascript Problem Overview
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: & / \ # , + ( ) $ ~ % .. ' " : * ? < > { }
Javascript Solutions
Solution 1 - Javascript
string = string.replace(/[&\/\\#,+()$~%.'":*?<>{}]/g,'_');
Alternatively, to change all characters except numbers and letters, try:
string = string.replace(/[^a-zA-Z0-9]/g,'_');
Solution 2 - Javascript
string = string.replace(/[\W_]/g, "_");