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?
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);
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>
["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-.