JavaScript | string.search()
The string.search() is an inbuilt function in JavaScript which is used to search for a match in between regular expressions and a given string object.
Syntax :
string.search(A)
Parameters: Here parameter “A” is a regular expression object.
Return Value: This function returns the index of the first match in between regular expression and the given string object and returns -1 if no match found.
Code #1:
Indexing starts from zero (0) and if at first attempt a alphabet is match, then it do not check further simply it return the index of that first matched alphabet.
<script> // Taking input a string. var string = "GeeksforGeeks"; // Taking a regular expression. var re1 = /G/; var re2 = /e/; var re3 = /s/; // Printing the index of matching alphabets document.write(string.search(re1) + "<br>"); document.write(string.search(re2) + "<br>"); document.write(string.search(re3)); < /script> |
Output:
0 1 4
Code #2:
Here in below code it can be seen that this function is only returning -1, because no matching found in between regular expression and input string.
<script> // Taking input a string. var string = "GeeksforGeeks"; // Taking a regular expression. var re1 = /p/; var re2 = /1/; var re3 = / /; var re4 = /, /; // Printing the index of matching alphabets document.write(string.search(re1) + "<br>"); document.write(string.search(re2) + "<br>"); document.write(string.search(re3) + "<br>"); document.write(string.search(re4)); < /script> |
Output:
-1 -1 -1 -1
Recommended Posts:
- Introduction to JavaScript Course | Learn how to Build a task tracker using JavaScript
- JavaScript Course | Understanding Code Structure in JavaScript
- JavaScript Course | Printing Hello World in JavaScript
- JavaScript Course | Logical Operators in JavaScript
- JavaScript Course | Conditional Operator in JavaScript
- JavaScript Course | Data Types in JavaScript
- JavaScript Course | Objects in JavaScript
- JavaScript Course | JavaScript Prompt Example
- JavaScript Course | Loops in JavaScript
- JavaScript Course | Variables in JavaScript
- JavaScript Course | Functions in JavaScript
- JavaScript Course | Operators in JavaScript
- JavaScript vs Python : Can Python Overtop JavaScript by 2020?
- How to include a JavaScript file in another JavaScript file ?
- JavaScript | Let
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.



