javascript
  1. javascript-search

JavaScript search()

Syntax

The syntax for the search() method in JavaScript is:

string.search(searchvalue)

where string is the string to be searched, and searchvalue is the value to search for. The search() method returns the index of the first occurrence of the search value in the given string, and -1 if the search value is not found.

Example

let str = "Hello World!";
let pos = str.search("World");
console.log(pos); // Output: 6

In this example, the search() method is used to search for the string "World" in the str variable. The method returns the index of the first occurrence of "World" in str, which is 6.

Output

The output of the search() method is the index of the first occurrence of the search value in the given string, and -1 if the search value is not found.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>JavaScript Output</title>
</head>
<body>

<!-- Your JavaScript code goes here -->
<script>
  let str = "Hello World!";

  // Using the search method to find the position of "World" in the string
  let pos = str.search("World");

  // Displaying the result in the HTML document
  document.write('<p>' + pos + '</p>');
</script>

</body>
</html>

Try Playground

Explanation

The search() method is used to search for a specified value in a string. The method returns the index of the first occurrence of the search value in the given string.

If the search value is found, the search() method returns the index of the first occurrence of the search value. If the search value is not found, the search() method returns -1.

Use

The search() method is commonly used to search for a specific pattern within a string. It can also be used to validate user input.

Important Points

  • The search() method is case-sensitive.
  • The search() method does not accept a regular expression as input. Instead, use the match() method with a regular expression to search for patterns in a string.
  • The method returns only the index of the first occurrence of the search value. If you need to find all occurrences of the search value, use the match() method with a regular expression.
  • The search() method can also be used with a regular expression inside the parenthesis.

Summary

The search() method is used to search for a specified value in a string. It returns the index of the first occurrence of the search value in the given string, and -1 if the search value is not found. The method is commonly used for pattern matching and input validation. The important points to remember when using the search() method are that it is case-sensitive, does not accept regular expressions, and returns only the index of the first occurrence of the search value.

Published on: