Home > Web Front-end > JS Tutorial > body text

How to search for a pattern in a string in JavaScript?

WBOY
Release: 2023-08-30 12:13:01
forward
1254 people have browsed it

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 -

Method 1

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.

Syntax

str.search( expression )
Copy after login

Parameters

  • 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.

Example 1

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




   
      Creating Objects from Prototype
   

Welcome To Tutorials Point

Copy after login

Output

如何在 JavaScript 中搜索字符串中的模式?

Example 2

below In the example, we create multiple regular expressions and check whether they meet the requirements on the string.

# index.html




   
      Creating Objects from Prototype
   

Welcome To Tutorials Point

Copy after login

output

如何在 JavaScript 中搜索字符串中的模式?

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!