How to create string with multiple spaces in JavaScript

前端 未结 5 619
北海茫月
北海茫月 2020-12-08 06:37

By creating a variable

var a = \'something\' + \'        \' + \'something\'

I get this value: \'something something\'.

相关标签:
5条回答
  • 2020-12-08 07:10

    In 2020 - use ES6 Template Literals for this task. If you need IE11 Support - use a transpiler.

    let a = `something       something`;
    

    Template Literals are fast, powerful and produce cleaner code.


    If you need IE11 support and you don't have transpiler, stay strong

    0 讨论(0)
  • 2020-12-08 07:14
    var a = 'something' + Array(10).fill('\xa0').join('') + 'something'
    

    number inside Array(10) can be changed to needed number of spaces

    0 讨论(0)
  • 2020-12-08 07:15

    With template literals, you can use multiple spaces or multi-line strings and string interpolation. Template Literals are a new ES2015 / ES6 feature that allows you to work with strings. The syntax is very simple, just use backticks instead of single or double quotes:

    let a = `something                 something`;
    

    and to make multiline strings just press enter to create a new line, with no special characters:

    let a = `something 
    
        
                             something`;
    

    The results are exactly the same as you write in the string.

    0 讨论(0)
  • 2020-12-08 07:25

    You can use the <pre> tag with innerHTML. The HTML <pre> element represents preformatted text which is to be presented exactly as written in the HTML file. The text is typically rendered using a non-proportional ("monospace") font. Whitespace inside this element is displayed as written. If you don't want a different font, simply add pre as a selector in your CSS file and style it as desired.

    Ex:

    var a = '<pre>something        something</pre>';
    document.body.innerHTML = a;
    
    0 讨论(0)
  • 2020-12-08 07:33

    Use &nbsp;

    It is the entity used to represent a non-breaking space. It is essentially a standard space, the primary difference being that a browser should not break (or wrap) a line of text at the point that this   occupies.

    var a = 'something' + '&nbsp &nbsp &nbsp &nbsp &nbsp' + 'something'
    

    Non-breaking Space

    A common character entity used in HTML is the non-breaking space (&nbsp;).

    Remember that browsers will always truncate spaces in HTML pages. If you write 10 spaces in your text, the browser will remove 9 of them. To add real spaces to your text, you can use the &nbsp; character entity.

    http://www.w3schools.com/html/html_entities.asp

    Demo

    var a = 'something' + '&nbsp &nbsp &nbsp &nbsp &nbsp' + 'something';
    
    document.body.innerHTML = a;

    0 讨论(0)
提交回复
热议问题