Adding whitespace to a string in typescript (in angular)

Discussão em 'Angular' iniciado por theonemc, Outubro 22, 2024.

  1. theonemc

    theonemc Guest

    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?

    Continue reading...

Compartilhe esta Página