118

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
  • 11,360
  • 15
  • 54
  • 77
user1049997
  • 1,553
  • 4
  • 14
  • 18

3 Answers3

271
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,341
  • 2
  • 31
  • 62
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
10
string = string.replace(/[\W_]/g, "_");
Wen
  • 2,227
  • 3
  • 24
  • 31
0

let myStr = "img_realtime_tr~ading3$ #Amoos !"

const replaceAccentsChars = (str, charWith='-', regexType='NO_SPECIAL' ) => {
  
    if(!str) return
  
    const REGEX_TYPE = {
      'ALL': / /g,
      'NO_SPECIAL': /[^A-Z0-9]/ig,
      'SINGLE_FOR_MULTI': /[^A-Z0-9]+/ig,
    }

    return str.replace(REGEX_TYPE[regexType], charWith).toLowerCase()
}


console.log(
  replaceAccentsChars(myStr)
)

// Speical Chars Allowed & String as params
console.log(
  replaceAccentsChars(myStr, '*', 'ALL')
)

console.log(
  replaceAccentsChars(myStr, '_', 'SINGLE_FOR_MULTI')
)
GMKHussain
  • 3,342
  • 1
  • 21
  • 19