Computer >> Computer tutorials >  >> Programming >> Javascript

Join arrays to form string in JavaScript


We are required to write a JavaScript function that takes in an array of strings. The function should join all the strings of the array, replace all the whitespaces with dash "-", and return the string thus formed.

For example, If the array is −

const arr = ["QA testing promotion ", " Twitter ", "Facebook ", "Test"];

Then the output should be −

const output = "QA-testing-promotion-Twitter-Facebook-Test";

Therefore, let’s write the code for this function −

Example

The code for this will be −

const arr = ["QA testing promotion ", " Twitter ", "Facebook ", "Test"];
const joinArr = arr => {
   const arrStr = arr.join('');
   let res = '';
   for(let i = 0; i < arrStr.length; i++){
      if(arrStr[i] === ' '){
         if(arrStr[i-1] && arrStr[i-1] !== ' '){
            res += '-';
         };
         continue;
      }else{
         res += arrStr[i];
      };
   };
   return res;
};
console.log(joinArr(arr));

Output

The output in the console will be −

QA-testing-promotion-Twitter-Facebook-Test