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:
- 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 Beginner." ; console.log(str); console.log(str.replace(/ /g, "_" )); |
A Computer Science portal for Beginner. A_Computer_Science_portal_for_Beginner.
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 Beginner." ; console.log(str); console.log(str.split( ' ' ).join( '_' )); |
A Computer Science portal for Beginner. A_Computer_Science_portal_for_Beginner.