Home > Enterprise >  Typescript concat string to string if he is avaialble
Typescript concat string to string if he is avaialble

Time:03-17

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

CodePudding user response:

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

CodePudding user response:

You can create a method that concats based on your conditions:

function concat(...theArgs) {
   return theArgs.reduce((previous, current) => {
       return current && current !== 'null' ? previous   current : previous;
   });
}

console.log(concat('original', 'string1', null));
console.log(concat('original', 'null', 'null'));

  • Related