How to join JavaScript array of string


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

Example

Following is the code −

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

This will produce the following output on console −

QA-testing-promotion-Twitter-Facebook-Test

Updated on: 01-Oct-2020

82 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements