Design & Download
Your JS Library
in Seconds!!!

Snippet: join()

Written by Christopher West (cwest) on November 29, 2015.
Glues the values of an array together to form a string.
function join(arr, opt_delimiter, opt_beforeEach, opt_afterEach) {
  opt_beforeEach = opt_beforeEach || '';
  opt_afterEach = opt_afterEach || '';
  return arr.length
    ? opt_beforeEach + arr.join(
        opt_afterEach
        + (opt_delimiter != undefined ? opt_delimiter : ',')
        + opt_beforeEach
      ) + opt_afterEach
    : '';
}

join(...) API Documentation

Description

Glues the values of an array together to form a string.

Parameters

  1. arr {Array}:
    The array containing the values to be glued together.
  2. opt_delimiter {string}:
    Optional. Defaults to ','. The string to delimit each value in arr.
  3. opt_beforeEach {string}:
    Optional. Defaults to the empty string. The string to prepend to each value in arr.
  4. opt_afterEach {string}:
    Optional. Defaults to the empty string. The string to append to each value in arr.

Returns

Returns a string representation of arr with all of the values prefixed by opt_beforeEach, suffixed by opt_afterEach and separated by opt_delimiter.

Example

console.log(YourJS.join([]));                          // -> ''
console.log(YourJS.join([1,2]));                       // -> '1,2'
console.log(YourJS.join([1,2], ';'));                  // -> '1;2'
console.log(YourJS.join([1,2], ';', '{', '}'));        // -> '{1};{2}'
console.log(YourJS.join([1,2,'Cool'], ';', '{', '}')); // -> '{1};{2};{Cool}'