split() and join() in Javascript 🔥

Опубликовано: 21 Март 2024
на канале: RoadsideCoder
4,077
211

In JavaScript, the split() and join() functions are used to manipulate strings. Here's an explanation of each function:

split(separator, limit):
The split() function is used to split a string into an array of substrings based on a specified separator.
It takes two optional parameters:
separator: Specifies the character or regular expression to use for splitting the string. If omitted, the entire string will be returned as the first (and only) element of the array.
limit: An optional integer that specifies a limit on the number of splits to be found. The remaining substring(s) will be added as the last element(s) of the array. If omitted, all occurrences of the separator are used to split the string.

Example:
const str = 'Hello,World,JavaScript';
const arr = str.split(','); // Splits the string at commas
console.log(arr); // Output: ['Hello', 'World', 'JavaScript']

In this example, the string is split at each comma, resulting in an array with three elements.

join(separator):

The join() function is used to join the elements of an array into a string, using a specified separator between each element.
It takes one optional parameter:
separator: Specifies the character or characters to use for separating the array elements when they are joined into a string. If omitted, a comma is used as the default separator.

Example:
const arr = ['apple', 'banana', 'orange'];
const str = arr.join(', '); // Joins array elements with a comma and a space
console.log(str); // Output: 'apple, banana, orange'

In this example, the array elements are joined into a string using a comma and a space as the separator.