So last time we covered what the split() method is, its parameters, and some basic examples. Today, we’re going to look at some more complicated examples.
In the next example from MDN, we’re going to use a Regular Expression to do our splitting. First we set up a string called “names” and then we print that string to the console. Then we assign the Regular Expression to a string called “re”. See what they did there? Anyway, the expression does this:
Then we split the expression and print it to the console.
Note that all the spaces and semicolons are gone.
In the next example, we are not going to split the entire string. We’re going to ask for the first three splits only, using the space character as the separator.
What we get back is:
Note that the substring “World.” (element) comes back with the period since that is NOT specified as a separator.
In our next example we’re going to use another Regular Expression:
\d – looks for a digit from 0 to 9
The paratheses on either side of the \d are called a “capturing group”. This will return what you used as a separator
So, for our results we get back:
We get the split string, but we also get the separators – the digits we looked for with the Regular Expression – note that element is 1, and element is 2. Note also that since we didn’t use the space character as the separator, element is two words with a space between them.
In the final example, MDN gets really fancy and chains a bunch of methods together. This was actually one of the FreeCodeCamp exercises from early on where we want to reverse a string.
So, what happens is,we use the split() method first with an empty string – that’s why we have (”) up there. Our result from just the split operation will be [a,s,d,f,g,h,j,k,l]. Then we reverse it and get [l,k,j,h,g,f,d,s,a]. Finally, we join the array and end up with ‘lkjhgfdsa’.
MDN helpfully notes that you can compare the initial string to the final string with the “===” operator to see if it was a palindrome, another FreeCodeCamp exercise.
And that’s it for the split() method!