0

New to Typescript\Angular, wanted to know if their was an easy way to format strings\remove null strings? So if town was empty string it would not show "NULL"

this.client = c;
this.clientFulladdress= `${this.client.Address}, ${this.client.Town}, ${this.client.County}, ${this.client.PostCode}` 
1
  • so what do you want to display when any of the strings is null? Commented Feb 17, 2018 at 13:08

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

5 Comments

He wants to show a 'NULL' string if it doesn't exist, not remove it altogether.
The question says: "So if town was empty string it would not show "NULL""
Thank you sir :) !
@D-W Isn't my answer is the better solution? Here you have to filter the array and then join it, where as no array is required in my solution. You just have to make add or with the variable.
@ArpitSancheti The reason I did it this way is so that we don't add a comma for a blank field. It stops us from getting results like "123, , , SE1 1SE", and instead returns "123, SE1 1SE"
0
 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 = 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 : ""}`;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.