In this article, we will search for a specific pattern and pass only the strings that match the given pattern. We will use the following method to implement this functionality -
In this method we will search for the string matching the given pattern and get it from the string. string.search() is a built-in method provided by JavaScript for searching strings. We can also pass a regular expression or a normal string in this method.
str.search( expression )
str - Defines the string to be compared.
Expression - Defines a string expression that will be compared to a string
This will return a string The index where the string has started to match, or "-1" will be returned if the string does not match.
In the following example, we compare a string with a regular expression and return its index if the string matches. If not, -1 will be returned.
#index.html
<!DOCTYPE html> <html> <head> <title> Creating Objects from Prototype </title> </head> <body> <h2 style="color:green"> Welcome To Tutorials Point </h2> </body> <script> const paragraph = 'Start your learning journey with tutorials point today!'; // any character that is not a word character or whitespace const regex = /(lear)\w+/g; console.log("Index: " + paragraph.search(regex)); console.log("Alphabet start: " + paragraph[paragraph.search(regex)]); // expected output: "." </script> </html>
below In the example, we create multiple regular expressions and check whether they meet the requirements on the string.
# index.html
<!DOCTYPE html> <html> <head> <title> Creating Objects from Prototype </title> </head> <body> <h2 style="color:green"> Welcome To Tutorials Point </h2> </body> <script> const paragraph = 'Start your learning journey with tutorials point today!'; // any character that is not a word character or whitespace const regex = /(lear)\w+/g; const regex1 = /(!)\w+/g; const regex2 = /(!)/g; console.log("Index: " + paragraph.search(regex)); console.log("Index: " + paragraph.search(regex1)); console.log("Index: " + paragraph.search(regex2)); console.log("Alphabet start: " + paragraph[paragraph.search(regex)]); // expected output: "." </script> </html>
The above is the detailed content of How to search for a pattern in a string in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!