The Ultimate Guide to JavaScript String Methods – Split
The split() method is one of the most useful string methods in JavaScript. It allows you to divide a string into an array of substrings by specifying a separator.
In this comprehensive guide, we‘ll cover everything you need to know about using split() effectively:
- Syntax and basics
- Splitting on different separators
- Limiting the number of splits
- Omitting separators from output
- Empty strings in output array
- Common use cases
- Splitting with regular expressions
- Differences from String.prototype.match()
- Browser compatibility
So whether you‘re a beginner or a seasoned JavaScript developer, read on to become a master at splitting strings!
Syntax and Basics
Here is the basic syntax for using split():
const splitArray = string.split(separator, limit);
separator: Specifies the character(s) where the string should be split. Optional—if omitted, the entire string will be placed in one substring.limit: Maximum number of splits. Optionalstring: The string to be split.splitArray: The array containing the splitted substrings.
Some key things to know:
split()dividesstringeach time it encountersseparator.- The original string is not altered.
- Separators are omitted from the returned array.
- Empty strings can appear in the returned array if
separatoris at the start/end ofstringor ifstringcontains consecutive separators.
Example: Splitting a string on spaces
const str = "Hello world, this is a string";
const splitStr = str.split(" ");
console.log(splitStr);
// ["Hello", "world,", "this", "is", "a", "string"]
This splits str on every space, omitting the spaces and returning an array of substrings.
Easy enough! Now let‘s look at splitting on different kinds of separators.
Splitting on Different Separators
The separator can be any sequence of characters, not just a single one.
Example: Splitting on multiple characters
const names = "Harry-Ron-Hermione";
const splitNames = names.split("-");
console.log(splitNames);
// ["Harry", "Ron", "Hermione"]
Here the separator is the dash character -. The returned array contains the names, without the dashes.
The separator can also be the empty string "":
const letters = "abc";
const splitLetters = letters.split("");
console.log(splitLetters);
// ["a", "b", "c"]
This splits letters between each character, effectively splitting on nothing.
Be careful not to confuse splitting on "" with splitting without a parameter:
const str = "Hello";
console.log(str.split()); // ["Hello"]
console.log(str.split("")); // ["H", "e", "l", "l", "o"]
Omitting the separator keeps the string as one substring rather than splitting between characters.
Limiting the Number of Splits
You can limit the number of substrings by passing a number as the second argument:
const sentence = "The quick brown fox jumps over the lazy dog";
const fewWords = sentence.split(" ", 5);
console.log(fewWords);
// ["The", "quick", "brown", "fox", "jumps"]
Here we are splitting on spaces, but limiting to only 5 substrings. The remaining words are condensed into the last substring:
"over the lazy dog"
Setting a limit is useful for grabbing just a portion of a string when you don‘t need the full split.
Omitting Separators in Output
As shown earlier, split() omits the separators themselves from the returned array.
For example:
const digits = "1,2,3,4,5";
const arrayDigits = digits.split(",");
console.log(arrayDigits);
// ["1", "2", "3", "4", "5"]
The commas are omitted. This is often the desired behavior, but can be surprising if you expect otherwise.
If you do want to include separators, you can capture them through regular expressions, covered later in this guide.
Dealing with Empty Strings
Notice in the previous digits example that no empty strings appear in the output array. That‘s because there were no consecutive commas.
However, if a string starts or ends with separators, or contains consecutive separators, empty strings will show up in the output:
const sentences = "This is the first sentence. This is the second sentence.";
const splitSentences = sentences.split(". ");
console.log(splitSentences);
// ["" , "This is the first sentence", " This is the second sentence.", ""]
We have empty strings at indexes 0 and 3 because the string starts and ends with our ". " separator.
Also note index 1 contains a leading space, while index 2 contains a trailing period. This is because of the consecutive separators ". " between sentences.
Dealing with empty strings requires some caution:
const array = splitStr[0];
console.log(array.length); // 0
This empty slot still counts as an entry when checking the array length or iterating. So be aware that empty strings may need special handling.
Techniques like .filter() or .join() can help remove empties when needed:
// Filter empty strings
const noEmpties = splitStr.filter(x => x != "");
// Join back to string
const newStr = noEmpties.join(" ");
So in summary, expect that:
- Separators at string start/end produce empties at array start/end.
- Consecutive separators produce empty strings between substrings.
Handle these wisely by filtering, joining, or simply being aware.
Now let‘s look at some of the most common use cases where split shines…
Common Use Cases
While split has many applications, these four split techniques are some of the most popular:
1. Split Sentences into Words
A common task is splitting blocks of text into individual words:
const paragraph = "This is a test paragraph. We will split it into individual words.";
const words = paragraph.split(" ");
console.log(words);
// ["This", "is", "a" ... "individual", "words."]
This provides an array of words without punctuation we can iterate through and analyze.
Be aware this only splits on spaces, leaving punctuation mixed in with words. We can improve this by first standardizing punctuation:
paragraph
.replace(".", " . ")
.replace(",", " , ")
.replace("?", " ? ")
.replace("!", " ! ");
const words = paragraph.split(" ");
Now periods, commas etc. will split into their own words.
2. Split Characters of a Word
We can iterate through the letters of a string by splitting on an empty separator:
const letters = "javascript";
const splitLetters = letters.split("");
splitLetters.forEach(char => {
// do something with char
});
This provides the array ["j", "a", "v" ... ] to iterate through.
3. Reverse Strings by Splitting
An array reversed with .reverse() can be joined back to a string.
So split –> reverse –> join flips the string order:
const str = "Hello World";
const reversed = str.split("").reverse().join("");
// reversed = "dlroW olleH"
Though slower than other methods, this does provide an easy way to reverse strings.
4. Split with Regular Expressions
So far we‘ve used simple strings as separators. For more complex splitting, regular expressions can be used instead:
const tags = "TypeScript <JS> JavaScript <Java> Java";
const regex = /<(.*?)>/g;
const languages = tags.split(regex);
console.log(languages);
// ["TypeScript ", "JS", " JavaScript ", "Java"]
Our regex matches content inside angle brackets, splitting the string on those matches.
Parentheses () around the regex capture the content between brackets. This captured content shows up in the output array rather than being omitted like the angle brackets.
So regular expressions give us precision when we need to match on patterns, not just fixed strings.
There‘s much more to cover with regex and split – enough to warrant its own guide! But this example demonstrates the basics of using a regex separator.
Split vs String.prototype.match()
JavaScript also provides a .match() method for finding matches in strings:
const str = "Hello world!";
const matches = str.match(/Hello/); // ["Hello"]
So when should .split() be used vs .match()?
- Use split() when you want to divide one large string into many substrings
- Use match() when you want to extract matching patterns within the string
.split() chops the entire string on separators. .match() pulls out matching pieces but keeps the string intact.
So in summary:
- split() – Split string into array
- match() – Find matching patterns in string
Browser Compatibility
The split() method has excellent browser support across all modern browsers, including IE9+. It is also available in Node.js.
So feel confident using split() without having to worry about cross-browser issues!
Summary
Let‘s review what we learned:
- split() divides strings into substrings using a separator
- Separators can be any strings or regex patterns
- Original string is not altered
- Separators are omitted in output array
- Limit argument controls number of splits
- Empty strings appear next to consecutive separators
- Common use cases:
- Split sentences into words
- Iterate through string characters
- Reverse strings
- Use regex for complex splitting
With this knowledge, you are now a split() expert!
Split strings like a pro on your next JavaScript project. And check back as we dive deeper into advanced use cases of split() in future guides!