Course contentsShow
← JavaScript
Lesson 1019 of 2,72323. SymbolsFree lesson

Symbol.split for Custom String Splitting

Define how String.prototype.split behaves when called with your object as the separator.

Symbol.split for Custom String Splitting

What you'll learn: How to control what happens when your custom object is used as a separator in String.prototype.split().


When you call "hello-world".split("-"), JavaScript looks for the Symbol.split method on the separator (in this case, the string "-"). You can define this method on your own objects to customize how string splitting works.

How It Works

By implementing Symbol.split on an object, you tell JavaScript exactly how to split a string when your object is passed to .split(). The method receives two arguments: the string being split and an optional limit.

const customSplitter = {
  [Symbol.split](str, limit) {
    // Split on vowels
    const parts = str.split(/[aeiou]/i);
    return limit !== undefined ? parts.slice(0, limit) : parts;
  }
};

console.log("hello world".split(customSplitter));
// ["h", "ll", " w", "rld"]

console.log("hello world".split(customSplitter, 2));
// ["h", "ll"]

Why This Matters

This well-known symbol lets you create intelligent separator objects that can handle complex splitting logic. For example, you might want a splitter that counts how many times it splits, or one that splits based on dynamic conditions.

const smartSplitter = {
  splitCount: 0,
  [Symbol.split](str) {
    this.splitCount++;
    return str.split(/\s+/); // Split on whitespace
  }
};

"one two three".split(smartSplitter);
console.log(smartSplitter.splitCount); // 1

Key Takeaway: Symbol.split lets you define custom splitting behavior by implementing a method that String.prototype.split() will call when your object is used as the separator.