Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

158
Views
Concatenate different variable if exist in JS

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
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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);

about 4 years ago · Juan Pablo Isaza Report

0

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);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!