---
title: "How to find the position of a matches string using Search() in JavaScript?"  
description: "How to find the position of a matches string using Search() in JavaScript?"  
author: "Utpal Vishwas"  
published: 2023-10-31  
updated: 2023-11-02  
canonical: https://www.mindstick.com/forum/160353/how-to-find-the-position-of-a-matches-string-using-search-in-javascript  
category: "javascript"  
tags: ["javascript", "regex", "javascript regex"]  
reading_time: 2 minutes  

---

# How to find the position of a matches string using Search() in JavaScript?

How to find the position of a matches [string](https://www.mindstick.com/articles/1527/string-split-in-c-sharp) using [Search](https://www.mindstick.com/articles/65368/best-smo-services-company-in-hyderabad-improve-search-rankings)() in [JavaScript](https://www.mindstick.com/articles/874/how-to-create-watermark-text-for-textbox-by-using-javascript)?

## Replies

### Reply by Aryan Kumar

\
In JavaScript, you can find the position of a matched string within a larger string using the **search()** method in conjunction with regular expressions. The **search()** method returns the index of the first occurrence of the matched substring in the string, or it returns -1 if no match is found. Here's how to use it:

```plaintext
const inputString = "Hello, I have 3 cats and 2 dogs, but I want more cats.";
const searchString = "cats";

const position = inputString.search(searchString);

if (position !== -1) {
  console.log(`The first occurrence of "${searchString}" starts at index ${position}.`);
} else {
  console.log(`"${searchString}" was not found in the input string.`);
}
```

In this example, we use the **search()** method to search for the string "cats" within the **inputString**. If a match is found, the **position** variable will contain the index where the first occurrence of "cats" starts in the string. If no match is found, **position** will be -1.

Keep in mind that the **search()** method works with plain strings, so it doesn't use regular expressions by default. If you want to use a regular expression for more complex pattern matching, you can modify the code like this:

```plaintext
const inputString = "Hello, I have 3 cats and 2 dogs, but I want more cats.";
const regex = /cats/g;

const
```

In this example, we use a regular expression to search for "cats" globally (**/cats/g**) and then access the **index** property of the match object to find the starting position of the matched substring.


---

Original Source: https://www.mindstick.com/forum/160353/how-to-find-the-position-of-a-matches-string-using-search-in-javascript

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
