Replace special characters in javascript

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

Replace special characters in javascript

jkdev

10.7k15 gold badges55 silver badges77 bronze badges

asked Mar 14, 2012 at 15:44

user1049997user1049997

1,4834 gold badges14 silver badges18 bronze badges

4

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

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

string = string.replace(/[^a-zA-Z0-9]/g,'_');

answered Mar 14, 2012 at 15:46

8

string = string.replace(/[\W_]/g, "_");

answered Jun 12, 2020 at 6:10

Replace special characters in javascript

Not the answer you're looking for? Browse other questions tagged javascript jquery or ask your own question.

This article discusses replacing all special characters in a javascript string using different methods and examples.

Table of Contents:-

  • Javascript replace regex special characters in a string using replace()
  • Javascript replace special characters in a string using a custom function

Javascript replace regex special characters in a string using replace()

The javascript replace() method replaces some or all occurrences of a pattern with a replacement(character/string). The pattern can be a character or a string, or regExp.

Syntax:-

replace(regexp, replacement)

Example:-

Advertisements

Replace all occurrences of all special characters with “” (empty) from the string “Javascript is @ a # language, This is : the most %popular _ language.”

let newString = ""
let dummyString = "Javascript is @ a # language, This is : the most %popular _ language."
newString = dummyString.replace(/[`[email protected]#$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/gi, '')
console.log(dummyString)
console.log(newString)

Output:-

Javascript is @ a # language, This is : the most %popular _ language.
Javascript is  a  language This is  the most popular  language

Here, in the replace() function, the first argument takes the characters which we want to replace. The second argument is the replacement character.

Note that here ‘,'(comma) and ‘.'(dot) are also removed. In case you want to retain, use:

let newString = ""
let dummyString = "Javascript is @ a # language, This is : the most %popular _ language."
newString = dummyString.replace(/[`[email protected]#$%^&*()_|+\-=?;:'"<>\{\}\[\]\\\/]/gi, '')
console.log(dummyString)
console.log(newString)

Output:-

Javascript is @ a # language, This is : the most %popular _ language.
Javascript is  a  language, This is  the most popular  language.

Example:-

Replace all occurrences of all special characters with “_” (underscore) from the string “Javascript is @ a # language, This is : the most %popular _ language.”

let dummyString = "Javascript is @ a # language, This is : the most %popular _ language."
newString = dummyString.replace(/[^a-zA-Z0-9][\W]/gi,'_')
console.log(dummyString)
console.log(newString)

Output:-

Javascript is @ a # language, This is : the most %popular _ language.
Javascript is_ a_ language_This is_ the most_popular _language.

Javascript replace special characters in a string using a custom function

In this section, we will be creating a function to replace the special characters in a javascript string. We can use this function to replace all special characters of our choice while retaining the ones we need in the string.

Example:-

Replace all occurrences of all special characters with “” (empty) but retain the ‘,’ (comma) and ‘.’ (dots) from the string “Javascript is @ a # language, This is : the most %popular _ language.”

let dummyString = "Javascript is @ a # language, This is : the most %popular  _language."
function replaceSpecialCharacters(_string) 
    {
    var lowerCase = _string.toLowerCase();
    var upperCase = _string.toUpperCase();
    var replacement = "";
    for(var i=0; i<lowerCase.length; ++i) {
        if(lowerCase[i] != upperCase[i] || lowerCase[i].trim() === '' || lowerCase[i].trim() === "." || 
        lowerCase[i].trim() === ",")
        replacement += _string[i];
    }
    return replacement;
}
let newString = replaceSpecialCharacters(dummyString)
console.log(newString)

Output:-

Javascript is  a  language, This is  the most popular  language.

The function will replace all the special characters with empty where whitespaces, comma, and dots are ignored. The concept is to compare the uppercase and lower case characters, and the characters with the same value for the upper and lower case are special characters, so remove them from the string.

Read More:

  • Javascript: Replace all occurrences of a character in string (4 ways)
  • Javascript: Replace all occurrences of string (4 ways)
  • Javascript check if string contains substring
  • Javascript: Check if string is empty (6 ways)

We hope this article helped you to replace all special characters in a javascript string. Good Luck !!!

How do you replace special characters?

To find and replace special characters, follow these steps:.
On the Home tab, in the Editing group, click Replace:.
In the Find and Replace dialog box, click the More > > button:.
Click the Special button, and select the special character or item you want to find and any text for which you want to search..

How do you change the special characters in a string?

Example of removing special characters using replaceAll() method.
public class RemoveSpecialCharacterExample1..
public static void main(String args[]).
String str= "This#string%contains^special*characters&.";.
str = str.replaceAll("[^a-zA-Z0-9]", " ");.
System.out.println(str);.

How do you change special characters in node JS?

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

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]+", "")