How to Split String in JavaScript: Syntax and Examples
In JavaScript, you can split a string into an array of substrings using the
split() method. You provide a separator string or regular expression inside split() to define where the string should be divided.Syntax
The split() method divides a string into an array of substrings based on a separator.
- separator: The character(s) or pattern where the string splits.
- limit (optional): Maximum number of elements in the resulting array.
javascript
string.split(separator, limit)
Example
This example shows how to split a sentence into words using a space as the separator.
javascript
const sentence = "Hello world from JavaScript"; const words = sentence.split(" "); console.log(words);
Output
["Hello", "world", "from", "JavaScript"]
Common Pitfalls
One common mistake is forgetting that split() returns an array, not a string. Also, using an empty string "" as a separator splits every character. If the separator is not found, the entire string is returned as one element.
javascript
const text = "apple,banana,orange"; // Wrong: expecting a string const wrong = text.split(","); console.log(typeof wrong); // "object" (it's an array) // Right: use the array const fruits = text.split(","); console.log(fruits[0]); // "apple"
Output
object
apple
Quick Reference
split(separator): splits by separator string or regex.split(""): splits into single characters.split(separator, limit): splits but returns maxlimitelements.- If separator is missing or
undefined, returns the whole string in an array.
Key Takeaways
Use
split() to divide a string into an array by a separator.The separator can be a string or a regular expression.
If separator is empty string, the string splits into characters.
Remember
split() returns an array, not a string.You can limit the number of splits with the optional second argument.