[英]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 來布局您的輸出。
而不是''你可以試試
正如人們在其他答案中對您發表的評論一樣,您的問題在於 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;
}
或者,如果您願意,可以將字符串結果嵌入到<pre></pre>
標記中。
您可以查看此頁面https://www.wikihow.com/Insert-Spaces-in-HTML以獲取更多信息。
即使您在字符串中獲得額外的空格,html 也不會呈現額外的空格。 您可以獲取所需的空格數並在任何需要的地方循環 html。 經過測試,它可以工作。
<span *ngFor="let i of whitespacecount"> </span>
您可以通過添加\xa0
添加空格。
例如:
result = result.concat("\xa0");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.