在其他字串中查詢字串出現的次數 - JavaScript
我們要編寫一個 JavaScript 函式,該函式接受兩個字串,並返回第一個字串在第二個字串中出現的次數
假設我們的字串為 −
const main = 'This is the is main is string';
我們必須在上面的“main”字串中查詢以下字串的出現 −
const sub = 'is';
讓我們為此函式編寫程式碼 −
示例
const main = 'This is the is main is string';
const sub = 'is';
const countAppearances = (main, sub) => {
const regex = new RegExp(sub, "g");
let count = 0;
main.replace(regex, (a, b) => {
count++;
});
return count;
};
console.log(countAppearances(main, sub));輸出
以下是控制檯中顯示的輸出 −
4
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式語言
C++
C#
MongoDB
MySQL
Javascript
PHP