Replace special characters in a string with _ (underscore)

前端 未结 2 1604
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-12 16:18

I want to remove special characters from a string and replace them with the _ character.

For example:

string = \"img_realtime_tr~ading3$         


        
相关标签:
2条回答
  • 2020-12-12 16:37
    string = string.replace(/[&\/\\#,+()$~%.'":*?<>{}]/g,'_');
    

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

    string = string.replace(/[^a-zA-Z0-9]/g,'_');
    
    0 讨论(0)
  • 2020-12-12 16:49
    string = string.replace(/[\W_]/g, "_");
    
    0 讨论(0)
提交回复
热议问题