How to find the position of a matches string using Search() in JavaScript?
How to find the position of a matches string using Search() in JavaScript?
14631-Oct-2023
Updated on 02-Nov-2023
Home / DeveloperSection / Forums / How to find the position of a matches string using Search() in JavaScript?
How to find the position of a matches string using Search() in JavaScript?
Aryan Kumar
02-Nov-2023In 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:
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:
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.