/**
* 計算子字串在主字串中出現的次數 (不重疊)
* @param {string} mainStr - 主字串
* @param {string} subStr - 要搜尋的子字串
* @returns {number} 出現次數
*/
function countInstances(mainStr, subStr) {
if (!subStr || subStr.length === 0) return 0; // 避免無限迴圈
var count = 0;
var offset = 0;
var idx;
while ((idx = mainStr.indexOf(subStr, offset)) !== -1) {
count++;
offset = idx + subStr.length; // 移至下一個可能位置 (不重疊)
}
return count;
}
subStr === "" 時 indexOf 永遠回傳 0,會導致無限迴圈,必須提前回傳 0。offset = idx + subStr.length 確保 "aaa" 中搜尋 "aa" 只算 1 次 (而非 2 次重疊)。indexOf 預設區分大小寫;若需不區分,先 toLowerCase() 兩字串再搜尋。function countInstancesAdvanced(mainStr, subStr, options) {
options = options || {};
var overlap = !!options.overlap; // 是否允許重疊
var ignoreCase = !!options.ignoreCase; // 不區分大小寫
if (!subStr) return 0;
var searchStr = ignoreCase ? mainStr.toLowerCase() : mainStr;
var searchSub = ignoreCase ? subStr.toLowerCase() : subStr;
var subLen = searchSub.length;
var count = 0;
var pos = 0;
var idx;
while ((idx = searchStr.indexOf(searchSub, pos)) !== -1) {
count++;
pos = overlap ? idx + 1 : idx + subLen;
}
return count;
}
// 測試
countInstancesAdvanced("aaaa", "aa"); // 2 (不重疊)
countInstancesAdvanced("aaaa", "aa", {overlap:true}); // 3 (重疊: 0-1, 1-2, 2-3)
countInstancesAdvanced("AbAbAB", "ab", {ignoreCase:true}); // 3
function countByRegex(str, subStr, ignoreCase) {
if (!subStr) return 0;
// 轉義特殊字元
var escaped = subStr.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
var flags = "g" + (ignoreCase ? "i" : "");
var regex = new RegExp(escaped, flags);
var matches = str.match(regex);
return matches ? matches.length : 0;
}
⚠️ 正則無法直接支援重疊匹配 (需用 lookahead 複雜寫法),且頻繁建立 RegExp 物件有效能開銷。
| 方法 | 耗時 (ms) | 備註 |
|---|---|---|
| while + indexOf | ~2 | 最快、記憶體穩定 |
| split().length - 1 | ~8 | 建立陣列額外記憶體 |
| RegExp + match | ~15 | 編譯正則開銷大 |
| replace 計數 | ~12 | 副作用修改字串 |
function keywordDensity(text, keyword) {
var totalWords = text.trim().split(/\s+/).length;
var kwCount = countInstances(text, keyword);
return (kwCount / totalWords * 100).toFixed(2) + "%";
}
var sensitive = ["賭博", "貸款", "色情", "詐騙"];
var content = Request.Form("article");
var alerts = [];
sensitive.forEach(function(w) {
var c = countInstances(content, w);
if (c > 3) alerts.push(w + " 出現 " + c + " 次");
});
if (alerts.length) { /* 送人工審核佇列 */ }
while + indexOf 是計算子字串出現次數的標準高效做法。記得處理空字串邊界、決定是否允許重疊、是否區分大小寫。若需 Unicode 輔助平面字元 (Emoji、生僻字) 正確計數,ES6+ 環境建議改用 [...str].join("") 或 Array.from 處理代理對,或引入 punycode/grapheme-splitter 庫。