Open In App

Create a string with multiple spaces in JavaScript

Last Updated : 29 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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. In this article, we are going to learn how to Create a string with multiple spaces in JavaScript.

Below are the methods to create a string with multiple spaces in JavaScript:

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() method

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

Method 3: Using String Concatenation

In this method, we concatenate ” ” in between the strings to add multiple spaces.

Example: In this example, we are Using String Concatenation.

Javascript




const stringWithSpaces = "This" + " " + "is" + " " + "a" + " " + "string" + "   " + "with" + "   " + "multiple" + "   " + "spaces.";
console.log(stringWithSpaces);


Output

This is a string   with   multiple   spaces.


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

Similar Reads