Open In App

Replacing spaces with underscores in JavaScript

Given a sentence and the task is to replace the spaces(” “) from the sentence with underscores(“_”) in JavaScript. There are some JavaScript methods are used to replace spaces with underscores which are listed 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: 



JavaScript split() method: This method is used to split a string into an array of substrings, and returns the new array. 

Syntax: 

string.split(separator, limit)

Parameters: 

Example 1: This example replaces all spaces(‘ ‘) with underscores(“_”) by using replace() method. 




let str = "A Computer Science portal for Geeks.";
 
console.log(str);
 
console.log(str.replace(/ /g, "_"));

Output
A Computer Science portal for Geeks.
A_Computer_Science_portal_for_Geeks.

Example 2: This example replaces all spaces(‘ ‘) with underscores(“_”) by using split() method. It first splits the string with spaces(” “) and then join it with underscore(“_”)




let str = "A Computer Science portal for Geeks.";
 
console.log(str);
 
console.log(str.split(' ').join('_'));

Output
A Computer Science portal for Geeks.
A_Computer_Science_portal_for_Geeks.
Article Tags :