[英]How to remove single quotes from array of strings and comma separate them into new array of strings
[英]Create address from multiple strings and separate them by comma
想象一下,我有5个字符串,其中任何一个都可以填写或保留为空(基于用户输入)
我想知道如何用逗号分隔它们。 我觉得这个问题一定很简单,但是我发现唯一可行但并不完全愚蠢的想法是:
// Create a function which return me string of arrays
public getAddress(): string[] {
let result = [];
if (this.application.applicant.city) {
result.push(this.application.applicant.city);
}
if (this.application.applicant.postalCode) {
result.push(this.application.applicant.postalCode);
}
if (this.application.applicant.state && this.application.applicant.state.name) {
result.push(this.application.applicant.state.name);
}
return result
}
// Then somewhere in ngOnInit() just call this method:
this.address = this.getAddress();
在我的tempalte内:
<span *ngFor="let item of address; let isLast=last">
{{item}}{{isLast ? '' : ', '}}
</span>
或经典JS方式:
<span> {{address.join(", ")}} </span>
而且我仍然觉得这太复杂了。 我是否缺少一些简单的解决方案?
谢谢你的建议
有一个打字稿功能分割 字符串 。 它还会删除,
this.addres = this.address.split(', '); // this is now an array instead of a string.
编辑
我创建了一个字符串,但是其中的newValue newValue可以是任何值。
let string = '';
if() {
string = `${string}, ${newValue}`;
}
这是一个比您的示例解决方案,您可以在方法中创建地址的字符串,然后直接在html模板中显示它(我认为比在数组上迭代更简单。)
在您的.ts中:
address : string ;
// Create a function which return me string of arrays
public getAddress(): string {
let result = "";
if (this.application.applicant.city) {
result.push(this.application.applicant.city+",");
}
if (this.application.applicant.postalCode) {
result.push(this.application.applicant.postalCode+",");
}
if (this.application.applicant.state && this.application.applicant.state.name) {
result.push(this.application.applicant.state.name+",");
}
if (result.length !== 0 )
result.substring(0, result.length-1);
return result
}
// Then somewhere in ngOnInit() just call this method:
this.address = this.getAddress();
在您的HTML模板中:
<span>{{address}}</span>
希望能帮助到你 :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.