您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

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

2024/5/30 23:01:22发布23次查看
在本文中,我们将搜索特定模式,并且仅传递与给定模式匹配的字符串。我们将使用以下方法来实现此功能 -
方法 1在这种方法中,我们将搜索与给定模式匹配的字符串,并从细绳。 string.search() 是 javascript 提供的用于搜索字符串的内置方法。我们还可以在此方法中传递正则表达式或普通字符串。
语法str.search( expression )
参数str - 定义需要比较的字符串。
表达式 - 定义将与字符串进行比较的字符串表达式
这将返回字符串的索引,其中字符串已开始匹配,如果字符串不匹配,将返回“-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>
输出
以上就是如何在 javascript 中搜索字符串中的模式?的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product