Onjsdev

Share


JavaScript Split() Method


By onjsdev

Jan 23rd, 2024

Javascript split() method splits a string into an array of substrings based on a specified separator. It's a convenient way to break down text into smaller chunks.

Syntax

Syntax of the split method is as shown below:

arr.split(separator, limit)
  • separator: specifies where the string should be split, it can be a string or regular expression.
  • limit(optional): specifies the maximum number of elements to include in the resulting array. If omitted or set to undefined, all elements are included.

Examples

Here is an example where we use the split() method to split the string at the comma character, resulting in an array containing two elements: 'Hello' and ' world!'

const myString = "Hello, world!";
const myArray = myString.split(",");
console.log(myArray); // Output: ["Hello", " world!"]

You can also use a regular expression as the separator, which allows you to split the string based on more complex patterns.

For example, you can split a string into words using the whitespace regex character(\s+/) as the separator:

const myString = "This is a test";
const myArray = myString.split(/\s+/);
console.log(myArray); // Output: ["This", ",is", "a", "test"]

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, you can extract the file extension from a file name using the pop() method as well as the split() method. The split method split the file name into an array, and then the pop() method extracts the last element of the array, which is the file extension.

const myString = "example.txt";
const myArray = myString.split(".");
const extension = myArray.pop();
console.log(extension); // Output: "txt"

Limit the Number of Substrings

The split method also allows to limit the number of substrings returned.

For example, you 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"]

Conclusion

In conclusion, the split is a method for manipulating strings in JavaScript. It allows you to split a string into an array including substrings based on a specified separator that can be a simple string or a regular expression.

If you are interested in sting and array methods in javascript. You can also see the article, the javascript array join method which is opposite of the split method in their functionalities.

Thank you for reading.