Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to join JavaScript array of string
We need to write a JavaScript function that joins an array of strings, replaces all whitespaces with dashes "-", and returns the formatted string.
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";
Method 1: Using Loop and String Concatenation
This approach joins the array elements and processes each character to replace spaces with dashes:
const arr = ["QA testing promotion ", " Twitter ", "Facebook ", "Test"];
const joinArr = arr => {
const arrStr = arr.join('');
let res = '';
for(let i = 0; i
QA-testing-promotion-Twitter-Facebook-Test
Method 2: Using join() and Regular Expression
A more concise approach using built-in string methods:
const arr = ["QA testing promotion ", " Twitter ", "Facebook ", "Test"];
const joinArrSimple = arr => {
return arr.join('').trim().replace(/\s+/g, '-');
};
console.log(joinArrSimple(arr));
QA-testing-promotion-Twitter-Facebook-Test
Method 3: Using map() and filter()
Clean approach that handles each array element separately:
const arr = ["QA testing promotion ", " Twitter ", "Facebook ", "Test"];
const joinArrClean = arr => {
return arr
.map(str => str.trim())
.filter(str => str.length > 0)
.join(' ')
.replace(/\s+/g, '-');
};
console.log(joinArrClean(arr));
QA-testing-promotion-Twitter-Facebook-Test
Comparison
| Method | Readability | Performance | Handles Edge Cases |
|---|---|---|---|
| Loop Method | Complex | Good | Yes |
| RegExp Method | Very Good | Excellent | Yes |
| map() + filter() | Excellent | Good | Yes |
Key Points
-
join('')combines array elements without separators -
trim()removes leading and trailing whitespace -
/\s+/gregex matches one or more consecutive spaces -
replace()substitutes matched patterns with dashes
Conclusion
The regular expression method provides the cleanest and most efficient solution for joining string arrays and replacing spaces with dashes. Use join('').trim().replace(/\s+/g, '-') for the best results.
Advertisements
