Open In App

Replacing spaces with underscores in JavaScript

Last Updated : 20 Jun, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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: 

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

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: 

  • separator: It is optional parameter. It specifies the character, or the regular expression, to use for splitting the string. If not used, the whole string will be returned (an array with only one item).
  • limit: It is optional parameter. It holds the integer that specifies the number of splits, items beyond the split limit will be excluded from the array.

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

Javascript




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(“_”)

Javascript




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.

Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads