Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

Create a string with multiple spaces in JavaScript

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

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. 

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  

html




<body style="text-align:center;" id="body">
    <h1 style="color:green;">
        GeeksForGeeks
    </h1>
    <h3>
        JavaScript
        |Create a string with multiple spaces.
    </h3>
    <p id="GFG_UP" style="font-size: 16px;">
    </p>
    <button onclick="gfg_Run()">
        Add spaces
    </button>
    <p id="GFG_DOWN" style="color:green;
            font-size: 20px;
            font-weight: bold;">
    </p>
    <script>
        var el_up = document.getElementById("GFG_UP");
        var el_down = document.getElementById("GFG_DOWN");
        var string = 'A Computer Science Portal';
        el_up.innerHTML = string;
          
        function gfg_Run() {
            el_down.innerHTML = string.substr(0, 2) +
            '     ' +
            string.substr(2);
        }
    </script>
</body>

Output:

Create a string with multiple spaces

Create a string with multiple spaces

Example 2: This example adds spaces to the string by \xa0(it’s a NO-BREAK SPACE char)

html




<body style="text-align:center;" id="body">
    <h1 style="color:green;">
        GeeksForGeeks
    </h1>
    <h3>
        JavaScript
        | Create a string with multiple spaces.
    </h3>
    <p id="GFG_UP" style="font-size: 16px;">
    </p>
    <button onclick="gfg_Run()">
        Add spaces
    </button>
    <p id="GFG_DOWN" style="color:green;
            font-size: 20px;
            font-weight: bold;">
    </p>
    <script>
        var el_up = document.getElementById("GFG_UP");
        var el_down = document.getElementById("GFG_DOWN");
        var string = 'A Computer Science Portal';
        el_up.innerHTML = string;
          
        function gfg_Run() {
            el_down.innerHTML = string.substr(0, 18) +
            '\xa0\xa0\xa0\xa0\xa0\xa0\xa0 ' +
            string.substr(18);
        }
    </script>
</body>

Output:

Create a string with multiple spaces

Create a string with multiple spaces


My Personal Notes arrow_drop_up
Last Updated : 05 Jan, 2023
Like Article
Save Article
Similar Reads
Related Tutorials