如何在 JavaScript 中创建带有多个空格的字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33539797/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 15:12:22  来源:igfitidea点击:

How to create string with multiple spaces in JavaScript

javascripthtmlwhitespacespacehtml-entities

提问by István

By creating a variable

通过创建变量

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

I get this value: 'something something'.

我得到这个值:'something something'.

How can I create a string with multiple spaces on it in JavaScript?

如何在 JavaScript 中创建一个带有多个空格的字符串?

回答by Andrew Evt

Use \xa0- it is a NO-BREAK SPACEchar.

使用\xa0- 它是一个NO-BREAK SPACE字符。

Reference from UTF-8 encoding table and Unicode characters, you can write as below:

参考UTF-8编码表和Unicode字符,可以这样写:

var a = 'something' + '\xa0\xa0\xa0\xa0\xa0\xa0\xa0' + 'something';

回答by Kishore Sahasranaman

Use  

 

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 ( ).

HTML 中常用的字符实体是不间断空格 ( )。

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  character entity.

请记住,浏览器总是会截断 HTML 页面中的空格。如果您在文本中写入 10 个空格,浏览器将删除其中的 9 个。要在文本中添加真实空间,您可以使用  字符实体。

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

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

Demo

演示

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

document.body.innerHTML = a;

回答by krmld

var a = 'something' + Array(10).fill('\xa0').join('') + 'something'

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

里面的数字Array(10)可以更改为所需的空格数

回答by Soupedenuit

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 preas a selector in your CSS file and style it as desired.

您可以将<pre>标记与innerHTML 一起使用。HTML<pre>元素代表预先格式化的文本,该文本将完全按照 HTML 文件中的书写方式呈现。文本通常使用非比例(“等宽”)字体呈现。此元素内的空白显示为书面形式。如果您不想要不同的字体,只需pre在您的 CSS 文件中添加一个选择器并根据需要设置样式。

Ex:

前任:

var a = '<pre>something        something</pre>';
document.body.innerHTML = a;