Create a string with multiple spaces in JavaScript
Last Updated :
29 Dec, 2023
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:
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
let string = "A Computer Science Portal" ;
console.log(string);
function gfg_Run() {
console.log(
string.substr(0, 2) + " " + string.substr(2)
);
}
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
let string = "A Computer Science Portal" ;
console.log(string);
function gfg_Run() {
console.log(
string.substr(0, 18) +
"\xa0\xa0\xa0\xa0\xa0\xa0\xa0 " +
string.substr(18)
);
}
gfg_Run();
|
Output
A Computer Science Portal
A Computer Science Portal
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
let string = "A Computer Science Portal" ;
console.log(string);
function gfg_Run() {
console.log(
string.substr(0, 2).padEnd(3, " " ) +
string.substr(2, 17) +
string.substr(18).padStart(3, " " )
);
}
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
Share your thoughts in the comments
Please Login to comment...