I want to concatenate different variable if exist and return the result. But I need to separate the value by "-" and return only the variable with value.
So I have this:
var test = "";
var test1 = "";
var test2 = "";
var test3 = "";
var checkTrue = "Rightt";
var checkFalse = "Wrong";
var checkWord = "Helloo";
var checkWord2 = "Bye";
if(checkTrue === "Right"){
test = "This is right"
} else {
test = "";
}
if(checkFalse === "Wrong"){
test1 = "This is wrong"
} else {
test1 = "";
}
if(checkWord === "Hello"){
test2 = "The word is hello"
} else {
test2 = "";
}
if(checkWord2 === "Bye"){
test3 = "The word is hello"
} else {
test3 = "";
}
var result = test " - " test1 " - " test2 " -" test3;
console.log(result);
So I think I need to verify before my var result, if the different variable exists ?
Thank for your help
Actual result:
- This is wrong - -The word is hello
Expected result :
This is wrong - The word is hello
CodePudding user response:
With anything where you want a separator between string values, I find it easier to use Array.prototype.join()
which will only place the separator between actual values.
It then becomes easier as you have a single results
array that can be joined, only adding values you want rather than testing each of those variables you no longer need.
By pushing on to an array you can also get rid of all those test
variables too.
const results = [];
const checkTrue = "Rightt";
const checkFalse = "Wrong";
const checkWord = "Helloo";
const checkWord2 = "Bye";
if (checkTrue === "Right")
results.push("This is right")
if (checkFalse === "Wrong")
results.push("This is wrong")
if (checkWord === "Hello")
results.push("The word is hello")
if (checkWord2 === "Bye")
results.push("The word is hello")
const result = results.join(" - ");
console.log(result);
CodePudding user response:
const test = '';
const test1 = 'This is wrong';
const test2 = '';
const test3 = 'The word is hello'
const result = [test, test1, test2, test3].filter(value => value).join(' - ');
console.log(result);