本例演示如何獲取網頁中所有出現的電子郵件地址。如果您需要更改網站特定頁面或子部分的電子郵件地址,此方法非常有用。雖然此處並非旨在用於從網頁抓取電子郵件地址,但這同樣也是一種可能的應用場景。查看更多 jQuery .each
示例。 i
表示不區分大小寫 (case insensitive),g
表示全局搜索,m
表示多行匹配
var iframeSrc = 'test.html?param=value&email=noobs@noob.com&moreparams=values'; var emailRegex= /[._a-zA-Z0-9-]+@[._a-zA-Z0-9-]+/igm; console.log(iframeSrc); console.log(emailRegex.test(iframeSrc)); console.log(iframeSrc.match(emailRegex)); $.each(iframeSrc.match(emailRegex), function(index, value) { console.log(index + ". " + value); }); //输出:0. noobs@noob.com
此代碼查找 <securequery></securequery>
標籤之間的所有 HTML 內容:
var secureQueryRegex = /(
/ 循環遍歷數據中找到的每個查詢 / $.each(data.match(secureQueryRegex), function(index, value) { console.log(index ". " value); });
jQuery 本身沒有內置函數來查找字符串中子字符串的所有出現位置。但是,您可以結合使用 JavaScript 的 match()
函數和全局正則表達式。示例如下:
var string = "Hello, world! Hello, user!"; var substring = "Hello"; var occurrences = string.match(new RegExp(substring, 'g'));
在此代碼中,g
標誌表示全局搜索,這意味著它將查找所有匹配項,而不僅僅是第一個匹配項。
match()
函數查找字符串中子字符串的出現位置嗎? 在 Python 中,您可以使用 count()
函數查找字符串中子字符串的所有出現次數。示例如下:
string = "Hello, world! Hello, user!" substring = "Hello" occurrences = string.count(substring)
在此代碼中,count()
函數返回子字符串在字符串中出現的次數。
您可以結合使用 count()
函數和 for
循環來查找字符串列表中子字符串的所有出現位置。示例如下:
list_of_strings = ["Hello, world!", "Hello, user!", "Goodbye, world!"] substring = "Hello" occurrences = [string.count(substring) for string in list_of_strings]
在此代碼中,for
循環迭代列表中的每個字符串,count()
函數查找子字符串在每個字符串中出現的次數。
match()
函數查找字符串中子字符串的出現位置嗎? 是的,您可以使用 JavaScript 中的 match()
函數查找字符串中子字符串的所有出現位置。但是,您需要將其與全局正則表達式結合使用,如問題 1 的答案所示。
您可以結合使用 while
循環和 indexOf()
函數來查找字符串中子字符串所有出現位置的索引。示例如下:
var iframeSrc = 'test.html?param=value&email=noobs@noob.com&moreparams=values'; var emailRegex= /[._a-zA-Z0-9-]+@[._a-zA-Z0-9-]+/igm; console.log(iframeSrc); console.log(emailRegex.test(iframeSrc)); console.log(iframeSrc.match(emailRegex)); $.each(iframeSrc.match(emailRegex), function(index, value) { console.log(index + ". " + value); }); //输出:0. noobs@noob.com
在此代碼中,while
循環持續進行,直到 indexOf()
函數返回 -1,表示無法再找到子字符串。出現位置的索引將存儲在 positions
數組中。
以上是jQuery在字符串中獲取字符串的所有出現的詳細內容。更多資訊請關注PHP中文網其他相關文章!