Skip to main content

jQuery Create Array From String

By Sam Deering

JavaScript

Share:

Free JavaScript Book!

Write powerful, clean and maintainable JavaScript.

RRP $11.95

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.

Sam Deering has 15+ years of programming and website development experience. He was a website consultant at Console, ABC News, Flight Centre, Sapient Nitro, and the QLD Government and runs a tech blog with over 1 million views per month. Currently, Sam is the Founder of Crypto News, Australia.

New books out now!

Learn valuable skills with a practical introduction to Python programming!


Give yourself more options and write higher quality CSS with CSS Optimization Basics.