Js split method
- Published
- Reading time
- 1 min read
- Length
- 294 words
On this page
Js Split Method#
The JavaScript split() method is used to split a string into an array of substrings based on a separator character. The separator can be a space, a comma, or any other character that you want to use to split the string.
Using the Split() Method#
To use the split() method in JavaScript, simply call the method on the string that you want to split and pass in the separator character as an argument. For example:
const myString = "This is a test string";
const myArray = myString.split(" ");
console.log(myArray); // output: ["This", "is", "a", "test", "string"]
In this example, we are splitting the string "This is a test string" using a space as the separator. The result is an array with five elements, each containing one of the substrings.
Multiple Separators#
You can also use multiple separators to split a string into an array. To do this, simply pass in a regular expression as the separator argument. For example:
const myString = "This,is;a-test-string";
const myArray = myString.split(/,|;|-/);
console.log(myArray); // output: ["This", "is", "a", "test", "string"]
In this example, we are using a regular expression to split the string using commas, semicolons, and hyphens as separators. The result is the same as the previous example.
Limiting the Number of Items in the Array#
You can also limit the number of items in the resulting array by passing in a second argument to the split() method. For example:
const myString = "This is a test string";
const myArray = myString.split(" ", 3);
console.log(myArray); // output: ["This", "is", "a"]
In this example, we are splitting the string using a space as the separator and limiting the number of items in the resulting array to three. The result is an array with only three elements.