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.
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
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
Please Login to comment...