0

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?

2
  • join Commented Sep 9, 2015 at 15:26
  • ["QA testing promotion ", " Twitter ", "Facebook ", "Test"].join(' ').split(' ').filter(function(item) {return item.length > 0}).join('-'), logic: 1. join to get a big string. 2. split by ' ', 3. filter out empty strings 4. join again, this time, by -. Commented Sep 9, 2015 at 15:27

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

Why not split by /\s+/ to avoid having to do the filter?
@torazaburo I'm not familiar with regex, thanks for the advice, I'll update my answer.
1

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

Comments

0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.