Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace special characters in a string with _ (underscore)

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

like image 226
user1049997 Avatar asked Mar 14 '12 15:03

user1049997


People also ask

How do you replace special characters in regex?

If you are having a string with special characters and want's to remove/replace them then you can use regex for that. Use this code: Regex. Replace(your String, @"[^0-9a-zA-Z]+", "")

How do you replace a special character in typescript?

To replace special characters, use replace() in JavaScript.

How do you change special characters in HTML?

replace(/>/g, "&gt;"). replace(/</g, "&lt;"). replace(/"/g, "&quot;");


2 Answers

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

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

string = string.replace(/[^a-zA-Z0-9]/g,'_'); 
like image 50
Niet the Dark Absol Avatar answered Sep 17 '22 13:09

Niet the Dark Absol


string = string.replace(/[\W_]/g, "_"); 
like image 36
Wen Avatar answered Sep 19 '22 13:09

Wen