Bharat  Bhushan
Bharat Bhushan

Reputation: 305

How to Join JavaScript array of string

I have an array of string variable object in this format:

["QA testing promotion ", " Twitter ", "Facebook ", "Test"]

I need to convert it into:

"QA-testing-promotion-Twitter-Facebook-Test"

Any ideas how to do this?

Upvotes: 0

Views: 119

Answers (3)

fuyushimoya
fuyushimoya

Reputation: 9813

UPDATE: Thanks to @torazaburo's advice, we can use /\s+/ to split the concatenated string by 1 or more spaces, thus avoid the .filter part of my original answer, then the code would be:

var result = 
     ["QA testing promotion ", " Twitter ", "Facebook ", "Test"]
      .join(' ')                                                // concate to get full string
      .split(/\s+/)                                        // split by `1 or more` space to create a new array.
      .join('-');                                             // join them again with '-'

console.log(result);

Upvotes: 3

Nina Scholz
Nina Scholz

Reputation: 386560

Just join the whole array with space and replace all non word items with dash.

document.write(
    ["QA testing promotion ", " Twitter ", "Facebook ", "Test"]
    .join(' ')
    .replace(/\W+/gi, '-')
);

Upvotes: 1

War10ck
War10ck

Reputation: 12508

You can use the built-in .trim() method for strings and .forEach() function for arrays to accomplish this:

var result = "";
["QA testing promotion ", " Twitter  ", "Facebook ", "Test"].forEach(function (element, index, array) {
    array[index] = (element.trim()).replace(/ /g, "-");
    if(index > 0) {
        result += "-" + array[index];  
    } else {
        result += array[index];  
    }
});

document.querySelector("#result").textContent = result; 
#result {
  margin-left: 10px;
  padding: 5px 10px;
  border: 1px solid #aaa;
  display: inline-block;
}
<label>Result</label>
<div id="result"></div>

Upvotes: 0

Related Questions