简体   繁体   English

打字稿和角度-格式字符串

[英]Typescript & Angular - Format String

New to Typescript\\Angular, wanted to know if their was an easy way to format strings\\remove null strings? Typescript \\ Angular的新手,想知道它们是否是格式化字符串\\删除空字符串的简便方法? So if town was empty string it would not show "NULL" 因此,如果镇是空字符串,则不会显示“ NULL”

this.client = c;
this.clientFulladdress= `${this.client.Address}, ${this.client.Town}, ${this.client.County}, ${this.client.PostCode}` 

Array functions are quite handy for this like this: 数组函数非常方便,例如:

let fields = [this.client.Address, this.client.Town, this.client.County, this.client.PostCode];

this.clientFulladdress = fields.filter((field) => field).join(", ");

This will filter out any null or empty strings, and then join each of the remaining string with a comma 这将筛选出任何空字符串或空字符串,然后将其余的每个字符串用逗号连接

 this.client = c;
 this.clientFulladdress= `${this.client.Address || ""}, ${this.client.Town || "" }, ${this.client.County || ""}, ${this.client.PostCode || ""}`;

This is the way you can achieve the required. 这是您达到要求的方式。

If you wish not to use this.client multiple time you can also do as follows 如果您不想多次使用this.client ,也可以执行以下操作

this.client = c;
let {Address, Town, Country, PostCode} = this.client;
this.clientFulladdress = `${Address || ""}, ${Town || ""}, ${Country || ""}, ${PostCode || ""}`;

As per comment other way to do the same 根据评论其他方式也可以

this.client = c;
let {Address, Town, Country, PostCode} = this.client;
this.clientFulladdress = `${Address || ""}${Town ? ", " + Town : ""}${Country ? ", " + Country : ""}${PostCode ? ", " + PostCode : ""}`;

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

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