JavaScript Symbol split Property

JavaScript Symbol split property is used to specify the method that splits a string at the indices that match a regular expression. This property is called by the String.split() method.

Syntax:

[Symbol.split](string)

Property attributes: It accepts a “String” which is not Writable, Enumerable, and Configurable.

Return value: It returns a string that is split from the given expression.

Below examples illustrate the Symbol split property in JavaScript:

Example 1: In this example, we will split the string and add (“”) in it.

Javascript




class Split1 {
    constructor(value) {
            this.value = value;
        }
        [Symbol.split](string) {
            const index = string.indexOf(this.value);
            return "'" + string.substr(0, index) + "' '" +
                this.value + "' '" + string.substr(index + this.value.length) + "'";
        }
}
  
console.log('w3wiki'.split(new Split1('for')));
console.log('Beginner1Beginner2Beginner3Beginner4'.split(new Split1('Beginner')));


Output:

"'Beginner' 'for' 'Beginner'"
"'' 'Beginner' '1Beginner2Beginner3Beginner4'"

Example 2: In this example, we will split the string and add (_) in it.

Javascript




class Split1 {
    constructor(value) {
            this.value = value;
        }
        [Symbol.split](string) {
            const index = string.indexOf(this.value);
            return "_" + string.substr(0, index) + "__" +
                this.value + "__" + string.substr(index + this.value.length) + "_";
        }
}
  
console.log('w3wiki'.split(new Split1('for')));
console.log('Computer Science Portal'.split(new Split1(' ')));


Output:

_Beginner__for__Beginner_
_Computer__ __Science Portal_

Supported Browsers: The browsers supported by JavaScript Symbol split property are listed below:

  • Google Chrome 51
  • Firefox 50
  • Edge 15
  • Opera
  • Apple Safari

We have a complete list of Javascript symbols’ properties and methods, to check those please go through the Javascript Symbol Complete Reference article.