Thursday, September 4, 2025
HomeLanguagesJavascriptReplace special characters in a string with underscore (_) in JavaScript

Replace special characters in a string with underscore (_) in JavaScript

In this article, we will see how to replace special characters in a string with an underscore in JavaScript. JavaScript replace() method is used to replace all special characters from a string with _ (underscore) which is described below:

JavaScript replace() Method: This method searches a string for a defined value, or a regular expression, and returns a new string with the replaced defined value. 

Syntax:

string.replace(searchVal, newvalue)

Parameters:

  • searchVal: It is a required parameter. It specifies the value or regular expression, that is going to replace by the new value.
  • newvalue: It is a required parameter. It specifies the value to replace the search value with.

Return value: It returns a new string that matches the pattern specified in the parameters.

Example 1: This example replaces all special characters with _ (underscore) using replace() method

Javascript




let str = "This, is# GeeksForGeeks!";
 
console.log(str.replace(/[&\/\\#, +()$~%.'":*?<>{}]/g, '_'));


Output

This__is__GeeksForGeeks!

Example 2: This example replaces a unique special character with _ (underscore). This example goes to each character and checks if it is a special character that we are looking for, then it will replace the character. In this example, the unique character is $(dollar sign). 

Javascript




let str = "A$computer$science$portal$for$Geeks";
 
function gfg_Run() {
 
    let newStr = "";
 
    for (let i = 0; i < str.length; i++) {
        if (str[i] == '$') {
            newStr += '_';
        }
        else {
            newStr += str[i];
        }
    }
    console.log(newStr);
}       
 
gfg_Run();


Output

A_computer_science_portal_for_Geeks

Example 3: In this example, we replace a unique special character with _ (underscore). This example spread function is used to form an array from a string and form a string with the help of reduce which excludes all special character and add underscore in their places. In this example the unique character are `&\/#, +()$~%.’”:*?<>{}`.

Javascript




let check = chr => `&\/#, +()$~%.'":*?<>{}`.includes(chr);
 
let str = "This, is# GeeksForGeeks!";
 
let underscore_str = [...str]
    .reduce((s, c) => check(c) ? s + '_' : s + c, '');
 
console.log(underscore_str);


Output

This__is__GeeksForGeeks!
RELATED ARTICLES

Most Popular

Dominic
32261 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6626 POSTS0 COMMENTS
Nicole Veronica
11795 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11855 POSTS0 COMMENTS
Shaida Kate Naidoo
6747 POSTS0 COMMENTS
Ted Musemwa
7023 POSTS0 COMMENTS
Thapelo Manthata
6695 POSTS0 COMMENTS
Umr Jansen
6714 POSTS0 COMMENTS