Thursday, September 4, 2025
HomeLanguagesJavascriptCreate a string with multiple spaces in JavaScript

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:

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 &nbsp

Javascript




// Input String   
let string = "A Computer Science Portal";
// Display input string
console.log(string);
 
// Funcion to add space
function gfg_Run() {
    console.log(
        string.substr(0, 2) + "     " + string.substr(2)
    );
}
 
// Function call
gfg_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 String
let string = "A Computer Science Portal";
// Display input string
console.log(string);
 
// Funcion to add space
function gfg_Run() {
    console.log(
        string.substr(0, 18) +
            "\xa0\xa0\xa0\xa0\xa0\xa0\xa0 " +
            string.substr(18)
    );
}
 
// Function call
gfg_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 String
let string = "A Computer Science Portal";
// Display input string
console.log(string);
 
// Funcion to add space
function gfg_Run() {
    console.log(
        string.substr(0, 2).padEnd(3, " ") +
            string.substr(2, 17) +
            string.substr(18).padStart(3, " ")
    );
}
 
// Function call
gfg_Run();


Output

A Computer Science Portal
A  Computer Science  Portal
RELATED ARTICLES

Most Popular

Dominic
32261 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6626 POSTS0 COMMENTS
Nicole Veronica
11795 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11855 POSTS0 COMMENTS
Shaida Kate Naidoo
6747 POSTS0 COMMENTS
Ted Musemwa
7023 POSTS0 COMMENTS
Thapelo Manthata
6695 POSTS0 COMMENTS
Umr Jansen
6714 POSTS0 COMMENTS