繁体   English   中英

向打字稿中的字符串添加空格(角度)

[英]Adding whitespace to a string in typescript (in angular)

我的一个组件中有一个方法,每当我单击一个按钮时,它就会在我的 html 页面中被调用。 我目前正在尝试格式化页面,以便某些属性(即城市和州)出现在页面的固定位置。 这是我到目前为止所拥有的:

if (this.city !== undefined) {
   let test = 50;
   test -= this.city.length;
   let result = 'City: ' + this.city;
   for ( let i = 0; i < test; i++) {
       result += ' ';
   }
   return result + this.state;
}

然而,而不是看到像城市这样的东西:

                                       (41 extra spaces) Grapevine TX

它看起来像城市:

Grapevine TX. 

有趣的是,只要不是空格,就会添加额外的字符。 例如,如果我写了 result += 'a',那么我会在字符串中看到 41 个额外的 a。

使用 result += 'a' 示例,如果我写了行 result = result.replace(/a/g, ' '),那么最终输出将是 City: Grapevine TX。 但是,如果我最初写了 result += ' ' 然后写了 result = result.replace(/ /g, 'a'),那么即使额外的空格不会出现在原始字符串中,这些空格也会被替换为一个'a'。

如何在我的字符串中添加额外的空格?

您的问题与 html 有关,它在另一个空格之后省略了多个空格。 角度不是根本原因。

纯 html 示例 - 两个标题均等显示:

 <h1>test test<h1> <h1>test test<h1>

解决方案:使用标签和/或 css 来布局您的输出。

尝试在您的 css 中使用下一个代码:

.pre-class {
    white-space: pre;
}

在此处输入图像描述

但要小心- 文本将按原样显示,所有空格和新行!

而不是''你可以试试&nbsp;

正如人们在其他答案中对您发表的评论一样,您的问题在于 html。 我建议你添加&nbsp; 而不是' '在您的代码中。

if (this.city !== undefined) {
   let test = 50;
   test -= this.city.length;
   let result = 'City: ' + this.city;
   for (let i = 0; i < test; i++) {
       result += '&nbsp;';
   }
   return result + this.state;
}

或者,如果您愿意,可以将字符串结果嵌入到<pre></pre>标记中。

您可以查看此页面https://www.wikihow.com/Insert-Spaces-in-HTML以获取更多信息。

即使您在字符串中获得额外的空格,html 也不会呈现额外的空格。 您可以获取所需的空格数并在任何需要的地方循环 html。 经过测试,它可以工作。

<span *ngFor="let i of whitespacecount">&nbsp;</span>

您可以通过添加\xa0添加空格。

例如:

result = result.concat("\xa0");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM