In this article we'll be taking a closer look at the
split() method and how we can use it in conjunction with regular expressions to split a long string just the way we want.
split(delimiter, limit) method is used on a string, it returns an array of substrings, and uses the
delimiter argument's value as the delimiter. The
delimiter argument can also be specified as a regular expression, which will then be used to search through the original string to find delimiters that match the specified expression.
Additionally, we can specify the optional argument
limit, which specifies how many elements we want in our resulting substring array. Setting
limit=2, for example, will yield an array that contains the first two substrings separated by a delimiter in the original string:
Here, the string will be broken down on each new word:
If we set the delimiter to something else, such as:
const chars = str.split(""); console.log(chars);
The string will be broken down on every character:
["J", "a", "v", "a", "S", "c", "r", "i", "p", "t", " ", "i", "s", " ", "t", "h", "e", " ", "b", "e", "s", "t", " ", "p", "r", "o", "g", "r", "a", "m", "m", "i", "n", "g", " ", "l", "a", "n", "g", "u", "a", "g", "e", "!"]
Regular Expressions with the split() Method
Now that we are comfortable with the use of the
split() method, let's step it up a notch, and introduce regular expressions to the mix:
const paragraph = `The Answer to the Ultimate Question of Life, the Universe, and Everything is 42. Forty two. That's all there is.`; // Split by words const words = paragraph.split(" "); console.log(words); // Split by sentences const sentences = paragraph.split(/[!?.]/); console.log(sentences); // Split all characters, with a limit of 2 const firstTwoChars = paragraph.split("", 2); console.log(firstTwoChars); // Split and reverse const reverse = paragraph.split("").reverse().join(""); console.log(reverse);
This results in:
to Forty two ["T", "h" ] .24 si gnihtyrevE dna ,esrevinU eht ,efiL fo noitseuQ etamitlU eht ot rewsnA ehT
In the second example, we are passing a regular expression as the argument for the
Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!
/[!?.]/represents a character set -
Put simply, we are splitting the string at any of the specified characters.
In the third example, we are passing
2 as the second argument, limiting the resulting substring array to two elements.
In the last example, we are reversing the string using the built-in
reverse() method. Because
reverse() is an array method, we'll first split the original string into an array of individual characters, by using the
split("") method, and then
Finally, we can
join() the results to create a reversed string from the array of characters.
split() method, as well as how to use it with regular expressions.