
Ans- The split method in JavaScript is used to split a string into an array of substring based on a specified separator and returns the new array.
Syntax:
JavaScript
string.split(separator, limit)Parameters:
- Separator: This parameter specifies the character or regular expression used to specify where to split the string. It can be a string or a regular expression. If omitted, the entire string will be a single element in the resulting array.
- limit: optional. An integer that specifies that maximum number of splits. The array will have most limit+1 element. If omitted, the entire string will be split.
Example:
JavaScript
var sentence = "This is my simple sentences";
var words = sentence.split(" ");
console.log(words); // [ 'This', 'is', 'my', 'simple', 'sentences' ]Example 2
JavaScript
var sentence = "This is a sample sentence with a lot of words";
var words = sentence.split(" ", 4);
console.log(words); //[ 'This', 'is', 'a', 'sample' ]In this example, the split(” “, 4) method splits the sentence string into an array of substrings using space as the delimiter. However, it specifies a limit of 4, which means it will create an array with at most 4 + 1 = 5 elements.
The resulting words array will contain the first four words from the sentence: [“This”, “is”, “a”, “sample”]. Since the limit was set to 4, the splitting stops after reaching the limit, and the rest of the sentence is not included in the array.
