Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Typescript concat string to string if he is avaialble

I have some values like this

let originalString = 'original'

let text1 = 'string1';
let text2 = 'string2';

I need to concat those text values in originalString, and final string should look like this

let originalString = 'original/string1/string2';

The problem I have is that sometimes one of the text string can be null, and then it has to remove from originalString, here is example with null

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

When second is null

let originalString = 'original'

let text1 = 'string1';
let text2 = null;

let originalString = 'original/string1';

When is null

let originalString = 'original'

let text1 = 'null';
let text2 = 'null';

let originalString = 'original';

And so on, maybe sometimes even all can be null, or two of them, anyway I need to add them in new string

>Solution :

You can push all of them into an array, and then your final array can be like this

const stringArray = ["original", null, "string2"]

Finally, you can use a filter to get NOT null values and then join them all

originalString = stringArray.filter(x => x).join("/")

In your example, you’re also using a 'null' string for values. You can add that value into your filter too.

originalString = stringArray.filter(x => x && x !== 'null').join("/")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading