How to Use Split and Join in JavaScript?

Estimated read time 1 min read

The split and join methods in JavaScript are used to convert strings to arrays and vice versa.

The split method takes a string and splits it into an array of substrings based on a specified separator. Here’s an example:

let str = "apple,banana,cherry";
let array = str.split(",");
console.log(array); // Output: ["apple", "banana", "cherry"]

In this example, the split method splits the string str into an array of substrings using the comma , as the separator. The resulting array is ["apple", "banana", "cherry"].

The join method takes an array and joins its elements into a single string, separated by a specified separator. Here’s an example:

let array = ["apple", "banana", "cherry"];
let str = array.join(",");
console.log(str); // Output: "apple,banana,cherry"

In this example, the join method joins the elements of the array into a single string, using the comma , as the separator. The resulting string is "apple,banana,cherry".

You can use these methods to convert strings to arrays and vice versa in various situations, such as when working with CSV (Comma-Separated Values) data, URL query parameters, and more.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply