by Sai gowtham

How to count string occurrences in a string JavaScript

To count the string occurrences in a given string, we can use the match() method in JavaScript.

The match() method accepts the regular expression as an argument and it returns the array of matched values.

Here is an example that counts the character ok in the following string.

const str = "he is ok, are you ok, hobby lol ok";
const count = str.match(/ok/g).length;

console.log(count); // 3

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
45,614 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
284,472 students enrolled
40 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
130,921 students enrolled
21 hours of video content
View Course