split()

ES3+

Divides a string into an ordered list of substrings and returns them as an array.

Syntax

string.split(separator, limit)

Parameters

separator string | RegExp

The pattern describing where each split should occur

limit number optional

Limit on the number of substrings to return

Return Value

Array

An Array of strings split at each point where the separator occurs

Examples

JavaScript
const str = 'Hello World';
console.log(str.split(' '));
console.log(str.split(''));
Output:
// ['Hello', 'World'] ['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']

📌 When to Use

Use split() when you need to break a string into parts based on a delimiter, such as parsing CSV data, extracting words from sentences, or processing user input with separators.

⚠️ Common Mistakes

Forgetting that split() with an empty string separator splits every character, which may not be the intended behavior.

Not handling the case when the separator is not found, which returns an array with the original string as the only element.

Using split() on user input without validating the input first, potentially causing unexpected results.

✅ Best Practices

Use the limit parameter when you only need a specific number of parts to improve performance on large strings.

Consider using regular expressions with split() for complex splitting patterns like multiple delimiters.

Chain with filter() to remove empty strings from the result when splitting might produce empty elements.

⚡ Performance Notes

split() creates a new array and new string objects for each element. For very large strings or frequent operations, consider using indexOf() with substring() in a loop for better memory efficiency. The limit parameter can significantly improve performance when you only need the first few parts.

🌍 Real World Example

Parsing CSV Data

A common use case is parsing comma-separated values from user input or file data. This example shows how to safely parse CSV rows with proper handling of edge cases.

// Parse CSV row into columns
function parseCSVRow(row) {
  // Split by comma and trim whitespace
  return row.split(',')
    .map(cell => cell.trim())
    .filter(cell => cell.length > 0);
}

const data = 'John, Doe, john@example.com, Developer';
const columns = parseCSVRow(data);
console.log(columns);
// Output: ['John', 'Doe', 'john@example.com', 'Developer']

// Parse URL query parameters
function parseQueryString(query) {
  return query.split('&').reduce((params, pair) => {
    const [key, value] = pair.split('=', 2);
    params[key] = decodeURIComponent(value || '');
    return params;
  }, {});
}

const query = 'name=John&age=30&city=Seoul';
console.log(parseQueryString(query));
// Output: { name: 'John', age: '30', city: 'Seoul' }

Related Methods