Replace special characters in a string with _ (underscore)

JavascriptJquery

Javascript 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, "_");

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1049997View Question on Stackoverflow
Solution 1 - JavascriptNiet the Dark AbsolView Answer on Stackoverflow
Solution 2 - JavascriptWenView Answer on Stackoverflow