Home > OS >  How to replace array commas with different characters in JS?
How to replace array commas with different characters in JS?

Time:10-05

Given this array ar and a list of separators:

let ar = ["bestes", "haus", "Tiangua"];
const separators = [" ", ""];

How can I convert it into a string, while using as separator each value from the separators array, instead of the usual commas?

Expected result:

res = ["bestes hausTiangua"]

This is my current implementation, but it would use the same separator only.

let kw = ar.join(',').replace.(/,/g, '/')

CodePudding user response:

You can do it in just one operation with the function Array.prototype.reduce:

ar.reduce((a, s, i) => a   separators[i-1]   s)

CodePudding user response:

Iterate over the array and shift from the separators every index.

const ar = ["bestes", "haus", "Tiangua"];
const separators = [" ", ""];

let str = ar[0];
for (let i = 1; i < ar.length; i  ) {
  str  = separators.shift()   ar[i];
}
console.log(str);

  • Related