Want to split a string up into several smaller strings using JavaScript? This is the article for you.
The JavaScript string.split() method will split up a string and return an array of strings. The string will be split at the position noted by a specified character. Here’s how to use it.
JavaScript string.split() Syntax
A method is a function or procedure available to run from an object or variable which will be run using the value from that variable.
The split() method is available on any string typed variable. Here’s the syntax:
string.split(separator, limit)
Note that:
- The split() method returns an array containing multiple strings – created by splitting the original string at the separator
- string can be any string variable
- separator should be the character or string which string will be split at
- The separator will be removed from the resulting array of split strings
- If no separator is supplied, the whole original string will be returned
- If an empty string is supplied as the separator, the string will be split at each character (so the result array will contain each character separately)
- limit is an optional parameter. Split strings numbering more than limit will be discarded from the results array
- It must be an integer (whole) number
Examples
Splitting Comma Separated Values
The split() method is frequently used to separate strings containing comma-separated values (CSV):
var commaSeparatedColours = "purple,orange,green,pink"; var coloursArray = commaSeparatedColours.split(','); // console.log(coloursArray); // Prints ['purple', 'orange', 'green', ']
Above, the string is split at the commas, creating an array of colors. The commas are discarded in the process.
Splitting Each Individual Character
To split a string between each character, use an empty string as the separator:
var myLetters = 'abcdefg'; var lettersArray = myLetters.split(''); console.log(lettersArray); // Prints ['a', 'b', 'c', 'd', 'e', 'f', 'g']
Limiting the Number of Split Strings
To limit the number of split strings included in the results, use the optional limit parameter:
var myLetters = 'abcdefg'; var lettersArray = myLetters.split('', 3); console.log(lettersArray); // Prints ['a', 'b', 'c' ]