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.
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:
- Declare a function called
countSubstringsthat takes two parameters:strandsearchValue. - Initialize two variables:
countandi. - Use the
Array.prototype.indexOf()method to search forsearchValueinstr. - If the value is found, increment the
countvariable and update theivariable. - Use a
whileloop that returns as soon as the value returned fromArray.prototype.indexOf()is-1. - Return the
countvariable.
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.