Count Substrings of String

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will explore the concept of counting substrings of a string using JavaScript. We will create a function that takes in a string and a search value and returns the number of times the search value appears in the string. This lab will help you understand the fundamentals of string manipulation in JavaScript and improve your problem-solving skills.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/BasicConceptsGroup -.-> javascript/cond_stmts("`Conditional Statements`") javascript/BasicConceptsGroup -.-> javascript/loops("`Loops`") subgraph Lab Skills javascript/variables -.-> lab-28223{{"`Count Substrings of String`"}} javascript/data_types -.-> lab-28223{{"`Count Substrings of String`"}} javascript/arith_ops -.-> lab-28223{{"`Count Substrings of String`"}} javascript/comp_ops -.-> lab-28223{{"`Count Substrings of String`"}} javascript/cond_stmts -.-> lab-28223{{"`Count Substrings of String`"}} javascript/loops -.-> lab-28223{{"`Count Substrings of String`"}} end

How to Count Substrings in a String using JavaScript

If you want to practice coding, open the Terminal/SSH and type node. This JavaScript function counts the number of occurrences of a specified substring in a given string.

To use this function, follow these steps:

  1. Declare a function called countSubstrings that takes two parameters: str and searchValue.
  2. Initialize two variables: count and i.
  3. Use the Array.prototype.indexOf() method to search for searchValue in str.
  4. If the value is found, increment the count variable and update the i variable.
  5. Use a while loop that returns as soon as the value returned from Array.prototype.indexOf() is -1.
  6. Return the count variable.

Here's the code for the countSubstrings function:

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;
  }
};

You can test the function using the examples below:

countSubstrings("tiktok tok tok tik tok tik", "tik"); // 3
countSubstrings("tutut tut tut", "tut"); // 4

Summary

Congratulations! You have completed the Count Substrings of String lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like