首頁 >web前端 >js教程 >jQuery在字符串中獲取字符串的所有出現

jQuery在字符串中獲取字符串的所有出現

Lisa Kudrow
Lisa Kudrow原創
2025-03-03 00:22:11973瀏覽

jQuery Get All Occurrences of a String inside a String

本例演示如何獲取網頁中所有出現的電子郵件地址。如果您需要更改網站特定頁面或子部分的電子郵件地址,此方法非常有用。雖然此處並非旨在用於從網頁抓取電子郵件地址,但這同樣也是一種可能的應用場景。查看更多 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 = /(

)/igm;

/ 循環遍歷數據中找到的每個查詢 / $.each(data.match(secureQueryRegex), function(index, value) { console.log(index ". " value); });

// 示例輸出: // 0. query=find all shops // 1. query=find all locations //等等... 關於在字符串中查找子字符串出現次數的常見問題 (FAQ)

如何使用 jQuery 查找字符串中子字符串的所有出現位置?

jQuery 本身沒有內置函數來查找字符串中子字符串的所有出現位置。但是,您可以結合使用 JavaScript 的 match() 函數和全局正則表達式。示例如下:

var string = "Hello, world! Hello, user!";
var substring = "Hello";
var occurrences = string.match(new RegExp(substring, 'g'));

在此代碼中,g 標誌表示全局搜索,這意味著它將查找所有匹配項,而不僅僅是第一個匹配項。

我可以在 Python 中使用 match() 函數查找字符串中子字符串的出現位置嗎?

在 Python 中,您可以使用 count() 函數查找字符串中子字符串的所有出現次數。示例如下:

string = "Hello, world! Hello, user!"
substring = "Hello"
occurrences = string.count(substring)

在此代碼中,count() 函數返回子字符串在字符串中出現的次數。

如何在 Python 中的字符串列表中查找子字符串的所有出現位置?

您可以結合使用 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() 函數查找子字符串在每個字符串中出現的次數。

我可以在 JavaScript 中使用 match() 函數查找字符串中子字符串的出現位置嗎?

是的,您可以使用 JavaScript 中的 match() 函數查找字符串中子字符串的所有出現位置。但是,您需要將其與全局正則表達式結合使用,如問題 1 的答案所示。

如何在 JavaScript 中查找字符串中子字符串所有出現位置的索引?

您可以結合使用 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中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn