JavaScript String search() method

The JavaScript string search() method determines a specified regular expression in a given string and returns its position if a match occurs.

Syntax:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
string.search(regexp)
string.search(regexp)
string.search(regexp)

Parameters:
regexp: It represents the regular expression to be searched.

Return:
It will return the position of the regular expression if it is present in the string otherwise returns -1.

Example:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<!DOCTYPE html>
<html>
<body>
<script>
var a ="Best tutorial website: w3schools";
document.write(a.search('co'));
document.write("</br>");
document.writeln(a.search(/web/));
document.write("</br>");
document.writeln(a.search(/web/i));
</script>
</body>
</html>
<!DOCTYPE html> <html> <body> <script> var a ="Best tutorial website: w3schools"; document.write(a.search('co')); document.write("</br>"); document.writeln(a.search(/web/)); document.write("</br>"); document.writeln(a.search(/web/i)); </script> </body> </html>
<!DOCTYPE html>
<html>
<body>
<script>
var a ="Best tutorial website: w3schools";
document.write(a.search('co'));
document.write("</br>");
document.writeln(a.search(/web/));
document.write("</br>");
document.writeln(a.search(/web/i));
</script>
</body>
</html>