Menu

gitpiper

countSubstrings javascript Code Snippet in 2023

stringalgorithmbeginner

Last Updated: 4 February 2023

Counts the occurrences of a substring in a given string.

  • Use Array.prototype.indexOf() to look for searchValue in str.
  • Increment a counter if the value is found and update the index, i.
  • Use a while loop that will return as soon as the value returned from Array.prototype.indexOf() is -1.
const countSubstrings = (str, searchValue) => { let count = 0, i = 0; while (true) { const r = str.indexOf(searchValue, i); if (r !== -1) [count, i] = [count + 1, r + 1]; else return count; } };
countSubstrings('tiktok tok tok tik tok tik', 'tik'); // 3 countSubstrings('tutut tut tut', 'tut'); // 4

javascript snippet similar to countSubstrings For You in February 2023

Subscribe to our Newsletter

Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️

© 2023 GitPiper. All rights reserved

Rackpiper Technology Inc

Company

About UsBlogContact

Subscribe to our Newsletter

Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️