The Wayback Machine - https://web.archive.org/web/20230317130426/https://www.geeksforgeeks.org/create-a-string-with-multiple-spaces-in-javascript/
Skip to content
Related Articles
Open in App
Not now

Related Articles

Create a string with multiple spaces in JavaScript

Improve Article
Save Article
  • Last Updated : 05 Jan, 2023
Improve Article
Save 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
Related Articles

Start Your Coding Journey Now!