Syntax of the split method is as shown below:
It takes one or two arguments:
- separator: It specifies where the string should be split, it can be a string or regular expression.
- optional limit: It specifies the maximum number of string characters that should be returned.
Here is an example of using the split method with a simple string:
const myString = "Hello, world!"; const myArray = myString.split(","); console.log(myArray); // Output: ["Hello", " world!"]
In this example, we use the split() method to split the string at the comma character, which results in an array containing two elements: "Hello" and " world!".
Split Method With Regex
We can also use a regular expression as the separator, which allows us to split the string based on more complex patterns. For example, we can split a string into words using the whitespace regex character as the separator:
const myString = "This is a test"; const myArray = myString.split(/\s+/); console.log(myArray); // Output: ["This", ",is", "a", "test"]
In this example, we use a regular expression that matches one or more whitespace characters (\s+) as the separator, it returns an array containing each word in the string.
Limit the Number of Substrings Returned
The split method also allows us to limit the number of substrings returned. For example, we can split an array into an array containing the number of elements specified by the limit parameter.:
const myString = "apple,banana,cherry,date"; const myArray = myString.split(",", 2); console.log(myArray); // Output: ["apple", "banana"]
In this example, we use a comma as the separator and set the limit to 2, which results in an array containing only the first two substrings: "apple" and "banana".
In addition to splitting a string into an array, the split method can also be used to extract a part of a string. For example, we can extract the file extension from a file name:
const myString = "example.txt"; const myArray = myString.split("."); const extension = myArray.pop(); console.log(extension); // Output: "txt"
In this example, we use a period as the separator to split the file name into an array, and then use the pop() method to extract the last element of the array, which is the file extension.
Thank you for reading.