Introduction
The split() method is one of the most useful string methods in JavaScript. It is used to divide a string into multiple parts and convert it into an array.
What is JavaScript split() Method?
The split() method divides a string into an array based on a specified separator.
Syntax of split()
string.split(separator, limit);
Explanation:
split() accepts two parameters.
- separator: Defines where to split the string.
- limit: Limits the number of returned elements.
Example:
let fruits = "Apple,Banana,Mango";
let result = fruits.split(",");
console.log(result);
Output:
Note: The comma acts as a separator.
Examples of split() Method
You will see some examples of the split() method.
Example 1: Split by Space
let text = "Learn JavaScript";
console.log(text.split(" "));
Output:
Example 2: Split by Comma
let fruits = "Apple,Banana,Mango";
console.log(fruits.split(","));
Output:
Example 3: Split Characters
let word="Hello";
console.log(word.split(""));
Output:
Example 4: Split with Limit
let word="H e l l o";
console.log(str.split(" ",2));
Output:
Real-Life Example of split()
Suppose a user enters skills: HTML,CSS,JavaScript
Convert into an array:
let skills = "HTML,CSS,JavaScript";
let result = skills.split(",");
console.log(result);
Output:
Common Mistakes in split()
Mistake 1: Forgetting the Separator
If you forget the separator, then no splitting occurs.
name = "John";
let result = name.split();
console.log(result);
Output:
Correct Way:
name = "John";
let result = name.split("");
console.log(result);
Output:
Mistake 2: Wrong Separator
Suppose you use the wrong separator.
Wrong:
name = "John Taylor";
let result = name.split(",");
console.log(result);
Output:
Correct separator:
name = "John Taylor";
let result = name.split(" ");
console.log(result);
Output:
Difference Between split() and slice()
| Feature | split() | slice() |
|---|---|---|
| Return Type | Array | String |
| Purpose | Divide string | Extract portion |
| Parameter | Separator required | Start/end index |
| Syntax | string.split(separator) |
string.slice(start, end) |
| Example |
let str = "HTML,CSS,JS";
|
let str = "JavaScript";
|
JavaScript split() Method – Interview Questions
Q 1: What does split() return?
Q 2: Syntax of split()?
Q 3: Difference between split() and join()?
join() → Array to string
Q 4: Can split() be used without separator?
Q 5: What will be output?
"Hello".split("")Conclusion
The JavaScript split() method is essential for converting strings into arrays. It is widely used in form handling, APIs, CSV processing, and text manipulation. Understanding split() improves JavaScript fundamentals and helps solve coding interview problems.