In JavaScript, the split method allows you to split the string into an array of substrings based on a given pattern. The split()
function takes one or two optional parameters, the first one being the separator, and the second the maximum number of elements to be included in the resulting array. If no separator is provided, the entire string is treated as one element in the resulting array.
What Is the Split Method in JavaScript?
The split method uses the split()
function in JavaScript. It allows you to split a string into an array of substrings based on a given pattern, and as a result, makes it easier to manipulate and work with strings.
Knowing how to use the split()
function in JavaScript is useful because it allows you to easily manipulate and work with strings. Here’s what you need to know.
When to Split a String in JavaScript
There are several reasons why you might want to split a string in JavaScript. A few examples include:
- Counting words: You can use
split()
to count the number of words in a string by splitting the string at every space character. - Extracting data from CSV Files: When working with comma-separated value (CSV) files, you can use
split()
to split each row into an array of values. - Parsing URLs: You can use
split()
to parse URLs by splitting a URL string at each forward-slash character, extracting the path and query parameters. - Removing/replacing substrings: You can use
split()
to remove or replace substrings from a string by splitting the string at the substring and concatenating the remaining parts together. - Converting strings to arrays: One of the main uses of
split()
is to convert a string into an array of substrings, which allows you to manipulate the elements of the string as discrete entities.
Overall, the split()
function is a powerful and versatile tool for working with strings and is an important method to know for any JavaScript developer.
How to Split a String in JavaScript
let numbersStr = "1,2,3,4,5";
let numArray = numbersStr.split(",");
console.log(numArray); // ["1","2","3","4","5"]
In the above example, the split method will loop through all the characters of the string to find a pattern of numbers. If the pattern provided is found, then the split method will collect the characters looped before finding the pattern and join all the characters as a string and push that string into an array.
If we don’t pass any pattern, then the entire string will be pushed to an array and return:
numbersStr.split(); // ["1,2,3,4,5"];
If the pattern passed is the first character of the string, then an empty string is pushed into the array.
numbersStr.split("1"); // ["", "2,3,4,5"]
Also, if the pattern passed is the last character of the string, then an empty string is pushed to the resultant array.
numbersStr.split("5")' // ["1,2,3,4", ""]
If we pass a pattern as an empty string, then each character of the string is split and pushed into an array.
numbersStr.split("");
// ["1", ",", "2", ",", "3", ",", "4", ",", "5"]
Limit Parameter
We can also pass the number of split operations to be done by passing the limit parameter.
numberStr.split(",", 2); // ["1", "2"]
If we pass limit as 0 then an empty string will be returned
numberStr.split(",", 0); // []
Split a String in JavaScript Examples
Below are two examples for how to split a string JavaScript.
1. Retrieve a Value From the CSS Property in JavaScript
Let’s say you want to get a value from the CSS property in JavaScript. Here’s how you could split a string to obtain that information.
let divHeight = document.getElementById("div1").style.height; //10px
let splittedArray = divHeight.split("px"); //[10, ‘’]
let height = splittedArray[0]; //10
console.log(height); // "10"
In the above code, we get the height of the document object module (DOM) element. The returned value will be 10px. If you want only the numerical part then we can use the split method to split the string with “px” value as a separator. When it’s split with “px” as a separator, we get an array with a numerical value as the first element. Then we can use that to get the height value.
2. Reverse a String
Let’s say we need to check if the given string is palindrome or not. To determine that, we first need to split the string into separate characters.
let name = "mom";
let splittedArray = name.split(""); // ["m", "o", "m"]
splittedArray.reverse(); // ["m", "o", "m"]
let reversedString = splittedArray.join(""); // mom
let isPalindrome = name === reversedString; // true
The split method returns an array. Then we use the reverse method to reverse the characters in the array. From there, we use the join method to create a string from the reversed array. This gives us the reversedString
.
Finally, we check for the equality of the original string and the reversed string. Since both strings are the same, they were palindromes and return the value true
. If they weren’t the same, they would not be a palindrome and would return false
.