如何加入JavaScript数组的字符串

时间:2015-09-09 15:23:57

标签: javascript javascript-objects

我有一个以这种格式的字符串变量对象数组:

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

我需要将其转换为:

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

任何想法如何做到这一点?

3 个答案:

答案 0 :(得分:3)

更新:感谢@torazaburo的建议,我们可以使用/\s+/将连接的字符串拆分1个或更多空格,从而避免原始的.filter部分回答,然后代码将是:



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




答案 1 :(得分:1)

只需用空格连接整个数组,并用破折号替换所有非单词项。

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

答案 2 :(得分:0)

您可以对字符串使用内置.trim()方法,为数组使用.forEach()函数来实现此目的:



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>
&#13;
&#13;
&#13;