[SOLVED] 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

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


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("/")

Answered By – Nick Vu

Answer Checked By – Jay B. (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *