Replace special characters in a string with _ (underscore)

前端 未结 2 1609
爱一瞬间的悲伤
爱一瞬间的悲伤 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,'_');
    

提交回复
热议问题