How to divide string into several parts with String split() in Javascript

Description

split() 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 sets the array limit. It ensures that the returned array will be no larger than a certain size.

Example


var colorText = "A,B,C,D"; 
var colors1 = colorText.split(","); //["A", "B", "C", "D"] 
console.log(colors1);//from  w w w.j  av  a  2 s.  c  o m
var colors2 = colorText.split(",", 2); //["A", "B"] 
console.log(colors2);
var colors3 = colorText.split(/[^\,]+/); //["", ",", ",", ",", ""] 
console.log(colors3);

The code above generates the following result.





















Home »
  Javascript »
    Javascript Reference »




Array
Canvas Context
CSSStyleDeclaration
CSSStyleSheet
Date
Document
Event
Global
History
HTMLElement
Input Element
Location
Math
Number
String
Window