DEV Community

Cover image for JS Array Methods: .join() and .split()
Ruky A
Ruky A

Posted on

JS Array Methods: .join() and .split()

Arrays

In Computer Science an Array Data Structure is a data structure that consists of a collection of elements.

In JavaScript, arrays are used to store multiple values in a single variable.

//creating a new array 
const arr1 = ["I", "am" , "just", "a" ,  "poor" ,  "array" ]
Enter fullscreen mode Exit fullscreen mode

Javascript arrays come with a lot of prebuilt methods. However, for the purpose of this post, we are going to be looking at the .join() and .split() method.

.join()

The .join() converts the elements of an array into a string and returns a new string

The join method can take an optional Parameter i.e arr1.join([seperator]).
if the separator is omitted the array elements are returned as a string with a comma to separate.

The following examples create an array, arr, with six elements, then joins the array four times: using the default separator, empty string, a space, then a dash

let arr1 = ["I", "am" , "just", "a" ,  "poor" ,  "array" ]; 

let string1 = arr1.join()

let string2 = arr1.join("")

let string3 = arr1.join(" ")

let string4 = arr1.join(" - ")

console.log(string1) // 'I,am,just,a,poor,array'
console.log(string2) //  Iamjustapoorarray'
console.log(string3)  //'I am just a poor array'
console.log(string4)  // 'I - am - just - a - poor - array'

Enter fullscreen mode Exit fullscreen mode

.split()

The split() method divides a String into an ordered list of substrings, puts these substrings into an array, and returns the array. You would normally use this when you want to make a string object iterable

The split method takes two parameters. - Separator and Limit

Separator
We have already seen how separators work in the examples above with .join(), they work the same. However, The .split() separator can either be a string or a regular expression.

Limit
If provided, it splits the string at each occurrence of the specified separator but stops when limit entries have been placed in the array.

let string = "I am just a poor string" 
let newArray = string.split()
let newArray1 = string.split('')
let newArray2 = string.split(' ')
let newArray3 = string.split(' ', 3)

console.log(newArray) // [ 'I am just a poor string' ]
console.log(newArray1)
/*
[
  'I', ' ', 'a', 'm', ' ',
  'j', 'u', 's', 't', ' ',
  'a', ' ', 'p', 'o', 'o',
  'r', ' ', 's', 't', 'r',
  'i', 'n', 'g'
]
*/
console.log(newArray2)//[ 'I', 'am', 'just', 'a', 'poor', 'string' ]
console.log(newArray3) // [ 'I', 'am', 'just' ]
Enter fullscreen mode Exit fullscreen mode

Top comments (0)