To convert array to space separated strings in javascript we can use the join()
method of an array, by passing the string with space as a parameter. the Array.join()
method returned the strings with spaces as an output.
The Array.prototype
.join()
method, this Array.join()
method is used to join(
) all the array with the specified characters.
Please refer to the below example we have passed the arr=[“javascript”,”typescript”,”react”,”angular”] to the arrValue to join(' ')
method of the array, then the join() method will return the values as space separated strings as an output. e.g ‘javascript typescript react angular’
The join()
method creates and returns a new string by concatenating all of the elements in an array
// ** convert array to space separated strings **
let arrValue = ['javascript', 'typescript', 'react', 'angular'];
const strValue = arrValue.join(' ');
console.log(strValue); // 'javascript typescript react angular'
console.log(typeof strValue); // string
if we called the array.join(’ ‘) method with an empty array, it will return the string with spaces.
console.log([].join(' ')); // ''
***************
Related Post(Array to Comma Separated Strings):
How to convert array to comma separated strings in javascript
*****************
the Array.prototype
.join()
will take the specified separator as the parameter in our case we have used space as a separator but if want to use a different separator we can use it it will be separated based on the specified separator character for example space, comma separated, “-”, “#”, or whatever you want.
For more details please find the below example.
const arrValue = ['javascript', 'typescript', 'react'];
const spaceAndComma = arrValue.join(', ');
console.log(spaceAndComma); // 'javascript, typescript, react'
const hash = arrValue.join('#');
console.log(hash); // 'javascript#typescript#react'
const hypens = arrValue.join('-');
console.log(hypens); // 'javascript-typescript-react'
const noSeparator = arrValue.join('');
console.log(noSeparator); // 'javascripttypescriptreact'
Please let me know if any clarifications to convert array to space separated strings in the comments. Thanks.
Leave a Reply