简体   繁体   中英

Adding whitespace to a string in typescript (in angular)

I have a method in one of my components that gets called in my html page whenever I click on a button. I am currently trying to format the page so that certain attributes (namely city and state) appear at fixed locations in the page. This is what I have so far:

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;
}

However, instead of seeing something like City:

                                       (41 extra spaces) Grapevine TX

it looks like City:

Grapevine TX. 

The interesting thing is that extra characters are added as long as they aren't spaces. For example, if I wrote result += 'a', then I would see 41 extra a's in the string.

Using the result += 'a' example, if I wrote the line result = result.replace(/a/g, ' '), then the final output would be City: Grapevine TX. However, if I had originally written result += ' ' and then wrote result = result.replace(/ /g, 'a'), then even though the extra spaces would not appear in the original string, those spaces would be replaced by an 'a.'

How do I add extra whitespace to my string?

Your issue is related to html which omits multiple spaces following another space. Angular is not the root cause.

Pure html Example - Both headlines are dispalyed equally :

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

Solution: use tags and/or css for layouting your output.

Try use next code in your css:

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

在此处输入图像描述

But be careful — text will be shown as is with all empty spaces and new rows!

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

As people have commented you in other answers, the problem in your case is with the html. I recommend you to add &nbsp; instead of ' ' in your code.

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;
}

Or if you prefer, you can embed your string result into <pre></pre> tags.

You can check out this page https://www.wikihow.com/Insert-Spaces-in-HTML for further information.

Even if you get extra spaces in string, html will not render the extra spaces. You can get the count of whitespaces needed and loop in html wherever wanted. Tested and it works.

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

You can add white spacess by adding \xa0 .

eg:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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