如何在 JavaScript 中計算字串中特定字串出現的次數
我們需要編寫一個 JavaScript 函式,其中包含兩個字串:str1 和 str2。然後,該函式應計數並返回 str2 在 strl 中出現的次數'
例如,−
count('this is a string', 'is') should return 2;
示例
用於此項工作的程式碼將為 −
const str1 = 'this is a string'; const str2 = 'is'; const countOccurrences = (str1, str2, allowOverlapping = true) => { str1 += ""; str2 += ""; if (str2.length <= 0) return (str1.length + 1); var n = 0, pos = 0, step = allowOverlapping ? 1 : str2.length; while (true) { pos = str1.indexOf(str2, pos); if (pos >= 0) { ++n; pos += step; } else break; } return n; }; console.log(countOccurrences(str1, str2));
產出
控制檯中的輸出將為 −
2
廣告