We are going to discuss the split() method in Node.js today.
What is the split() Method?
The string is divided based on a pattern which is passed in the first argument when calling the method.
The syntax looks like this:
separator – accepts a character or a regular expression. If nothing passed, it will return the entire string inside an array.
[limit] – a limit that you may specify as an integer. It is optional.
The split() method will not change the original string in any way. Which means you can access it over and over again.
If we pass a blank separator to this method, it will perform a character split. Meaning, every character inside the string is separated.
When we pass a space character to the separator, it will perform a words split.
Getting Started Splitting a String
This method is only available on strings. A string may be situated anywhere. For example, simply in a variable, or in an array, or stored in an object.
Split a string into variables
Let us split every character in a string that is stored in a studentName variable, using the split() method.
// ["S", "a", "r", "a", "h", " ", "L", "e", "e"]
Next, let’s pass a string with a space character:
// ["Sarah", "Lee"]
Now, let us pass a limit to split our characters.
// ["S", "a", "r", "a"]
// Let’s add more words and test out words split
const sarahZodiac = 'Sarah is a Gemini'
sarahZodiac.split(' ', 2)
// ["Sarah", "is"]
Split a String from an Array
Let’s say we have an array of names with us, saved like this:
To select a name, we will first select the array and then one of the strings using the index.
// ["B", "a", "m", "i", "d", "e", "l", "e", " ", "O", "n", "i", "b", "a", "l", "u", "s", "i"]
Split a String from an Object
Let us create a new productList object, for this example:
productList.name.split(' ', 3)
// ["Nike", "Air", "Force"]
Passing Characters to the Separator Parameter
So, we haven’t yet tried passing any characters to the separator parameter. Let us take a look at that.
// ["", "e Air Force 1"]
The output we have here indicates the characters we specified in the separator argument, have been chopped off of the string and split in half.
So, these are all the ways you can split a string.