- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements
To Continue Learning Please Login
Login with Google