Javascript - String Splitting Method

Introduction

The split() method separates the string into an array of substrings based on a separator.

The separator may be a string or a RegExp object.

An optional second argument, the array limit, ensures that the returned array will be no larger than a certain size.

var colorText = "red,blue,green,yellow,black";
var colors1 = colorText.split(",");      //["red", "blue", "green", "yellow", "black"]
var colors2 = colorText.split(",", 2);   //["red", "blue"]
var colors3 = colorText.split(/[^\,]+/); //["", ",", ",", ",",",",""]

In this example, the string colorText is a comma-separated string of colors.

The call to split(",") retrieves an array of those colors, splitting the string on the comma character.

To truncate the results to only two items, a second argument of 2 is specified.

Last call is using a regular expression, it's possible to get an array of the comma characters.

The last call to split() returned array with an empty string before and after the commas.

This happens because the separator specified by the regular expression appears at the beginning of the string (the substring "red") and at the end (the substring "yellow").

Related Topics