110

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

jkdev
  • 10,404
  • 15
  • 54
  • 77
user1049997
  • 1,473
  • 4
  • 14
  • 18

2 Answers2

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

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

string = string.replace(/[^a-zA-Z0-9]/g,'_');
Jacob Tomlinson
  • 3,083
  • 2
  • 29
  • 58
Niet the Dark Absol
  • 311,322
  • 76
  • 447
  • 566
4
string = string.replace(/[\W_]/g, "_");
Wen
  • 2,148
  • 3
  • 22
  • 30