Open In App

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

Last Updated : 26 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

We will explore several methods to replace special characters in a string with an underscore (_) in JavaScript. Special characters are non-alphanumeric symbols, and replacing them is a common requirement in various use cases such as sanitizing input or formatting file names.

JavaScript replace() Method

The JavaScript replace() Method searches for a defined value (or pattern) within a string and returns a new string where the matched values are replaced by a specified value.

Syntax:

string.replace(searchVal, newvalue);

Parameters:

  • searchVal: It is a required parameter. It specifies the value or regular expression, that is going to be replaced 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: Replacing All Special Characters with an Underscore

This example replaces all special characters with _ (underscore) using the replace() method

JavaScript
let str = "This, is# GeeksForGeeks!";

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

Output
This__is__GeeksForGeeks!

Example 2: Replacing a Specific Special Character

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: Replacing Multiple Special Characters

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!

Lodash _.replace() Method

In this approach, we are using Lodash _.replace() Method for replacing the special character into “_”. This example is the implementation of the above-explained approach.

JavaScript
// Requiring the lodash library 
const _ = require("lodash");

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

// Using the _.replace() method
let replace_elem = _.replace(string);

// Printing the output 
console.log(replace_elem);

Output:

Stay__In


Next Article

Similar Reads