Create a string with multiple spaces in JavaScript

We have a string with extra spaces and if we want to display it in the browser then extra spaces will not be displayed. Adding the number of spaces to the string can be done in the following ways.
Methods to Add Multiple Spaces in a String:
- Using the JavaScript substr() Method
- Using padStart() and padEnd() methods
Method 1:Using the JavaScript substr() Method
This method gets a part of a string, starts at the character at the defined position, and returns the specified number of characters.
Syntax:
string.substr(start, length)
Example 1:This example adds spaces to the string by  .
Javascript
// Input String let string = "A Computer Science Portal";// Display input stringconsole.log(string);// Funcion to add spacefunction gfg_Run() { console.log( string.substr(0, 2) + " " + string.substr(2) );}// Function callgfg_Run(); |
Output
A Computer Science Portal A Computer Science Portal
Example 2: This example adds spaces to the string by \xa0(it’s a NO-BREAK SPACE char).
Javascript
// Input Stringlet string = "A Computer Science Portal";// Display input stringconsole.log(string);// Funcion to add spacefunction gfg_Run() { console.log( string.substr(0, 18) + "\xa0\xa0\xa0\xa0\xa0\xa0\xa0 " + string.substr(18) );}// Function callgfg_Run(); |
Output
A Computer Science Portal A Computer Science Portal
Method 2: Using padStart() and padEnd() methods
These methods are used to add padding or spaces in the start and end respectively.
Example: In this example, we will use the above methods with the substr() method to add spaces in the string.
Javascript
// Input Stringlet string = "A Computer Science Portal";// Display input stringconsole.log(string);// Funcion to add spacefunction gfg_Run() { console.log( string.substr(0, 2).padEnd(3, " ") + string.substr(2, 17) + string.substr(18).padStart(3, " ") );}// Function callgfg_Run(); |
Output
A Computer Science Portal A Computer Science Portal



