JavaScript | Symbol.search Property

The Symbol.search property in JavaScript is a well-known symbol determines the method that returns the index within a string that matches the regular expression. This function is called by the String.prototype.search() method.

Syntax:

[Symbol.search](string)

Parameters: It accepts single parameter “String”.



Return value: This returns the position of a string where it matches and if not matches it will return -1.

Below examples illustrate the Symbol.search property in JavaScript:

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// JavaScript example to illustrate
// Symbol.search property
class obj {
  constructor(value) {
    this.value = value;
  }
  [Symbol.search](string) {
    return string.indexOf(this.value);
  }
}
  
console.log('Geeksforgeeks'.search(new obj('Geek')));
console.log('Geeksforgeeks'.search(new obj('geek')));

chevron_right


Output:

> 0
> 8

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// JavaScript program to illustrate
// the Symbol.search property
class S {    
  constructor(value) {  
    this.value = value;  
  }  
  [Symbol.search](string) {  
    return string.indexOf(this.value);  
  }  
}  
console.log('GEEKSFORGEEKS'.search(new S('geek')));  
console.log('GEEKSFORGEEKS'.search(new S('Geek')));

chevron_right


Output:

-1
-1

Supported Browsers: The browsers supported by Symbol.search property are listed below:

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

Reference: https://devdocs.io/javascript/global_objects/symbol/search

full-stack-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.