jQuery Create Array From String

Sam Deering

Simple jQuery code snippet to create an array from a string. Convert your string words into an array using jQuery split() command which is like the PHP explode() method.

var numbersString = "1,2,3,4,5,6";
var numbersArray = numbersString.split(',');


You can then loop through the values of the array like so:

$.each(numbersArray, function(index, value) { 
  alert(index + ': ' + value);
});

You can also join back your array items like so:

var numbersArray = new Array("1", "2", "3", "4", "5", "6");
var numbersString = numbersArray.join(',');
alert(numbersString); 
//alerts 1,2,3,4,5,6

Don’t forget to put your jQuery code inside a document ready function. See 4 different jQuery document ready examples for more info.

Win an Annual Membership to Learnable,

SitePoint's Learning Platform

  • Rwerewrewr

    erewrew ere re

  • surfer

    found an error in line 2, first chunk of code:

    var numbersArray = numbers.split(‘,’);
    should be
    var numbersArray = numbersString.split(‘,’);
    keep up the good work!

    • http://jquery4u.com/ jQuery4u

      Thanks mate

  • Martin

    Just what I needed :) thanks

  • http://www.facebook.com/vncoder Vũ Hùng

    thank very much

  • http://gaetanmasson.fr/ Gaëtan Masson

    Thanks! Exactly what I needed. :)