JavaScript에서 문자열의 패턴을 검색하는 방법은 무엇입니까?

WBOY
풀어 주다: 2023-08-30 12:13:01
앞으로
1318명이 탐색했습니다.

이 글에서는 특정 패턴을 검색하여 주어진 패턴과 일치하는 문자열만 전달해 보겠습니다. 이 기능을 구현하기 위해 다음 방법을 사용할 것입니다.

방법 1

이 방법에서는 주어진 패턴과 일치하는 문자열을 검색하여 문자열에서 가져옵니다. string.search()는 문자열 검색을 위해 JavaScript에서 제공하는 내장 메서드입니다. 이 메서드에서는 정규식이나 일반 문자열을 전달할 수도 있습니다.

Syntax

str.search( expression )
로그인 후 복사

Parameters

  • str - 비교할 문자열을 정의합니다.

  • Expression - 문자열과 비교할 문자열 표현식을 정의합니다.

이는 문자열이 일치하기 시작한 문자열의 인덱스를 반환하며, 문자열이 일치하지 않으면 "- 1"을 반환합니다. .

예제 1

아래 예에서는 문자열을 정규 표현식과 비교하고 문자열이 일치하면 해당 인덱스를 반환합니다. 그렇지 않은 경우 -1이 반환됩니다.

#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 = &#39;Start your learning journey with tutorials point today!&#39;;
      // 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>
로그인 후 복사

Output

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

예제 2

아래 예에서는 여러 정규식을 만들고 문자열에서 요구 사항을 충족하는지 확인했습니다.

# 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 = &#39;Start your learning journey with tutorials point today!&#39;;
      // 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>
로그인 후 복사

output

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

위 내용은 JavaScript에서 문자열의 패턴을 검색하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:tutorialspoint.com
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!