如何在 JavaScript 中搜索字符串中的模式?
在本文中,我们将搜索特定的模式,并且只通过那些与给定模式匹配的字符串。我们将使用以下方法来实现此功能:
方法 1
在这种方法中,我们将搜索与给定模式匹配的字符串,并从字符串中找到它们的索引。string.search() 是 **JavaScript** 提供的用于搜索字符串的内置方法。我们还可以在此方法中传递正则表达式或普通字符串。
语法
str.search( expression )
参数
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 = '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>输出

示例 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 = '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>输出

广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP