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(',');
//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.

Tags: alternative to PHP explode, jquery explode array, jquery split method, string words into an array
Sam Deering is a Front-end Web Developer who specialises in JavaScript & jQuery. Sam is driven and passionate about sharing his knowledge to educate others.

Free Guide:

How to Choose the Right Charting Library for Your Application

How do you make sure that the charting library you choose has everything you need? Sign up to receive this detailed guide from FusionCharts, which explores all the factors you need to consider before making the decision.

  • 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!

    • jQuery4u

      Thanks mate

  • Martin

    Just what I needed :) thanks

  • Vũ Hùng

    thank very much

  • Gaëtan Masson

    Thanks! Exactly what I needed. :)

  • Jynx

    This is pure javascript, not a jQuery method.

  • Skythe

    WHY ON MOFO EARTH is typeOf numbersArray ALWAYS undefined instead of array?
    Who came up with this broken language?? Seriously.

Special Offer
Free course!

Git into it! Bonus course Introduction to Git is yours when you take up a free 14 day SitePoint Premium trial.