Index of Substrings

JavaScriptJavaScriptBeginner
Practice Now

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

Introduction

In this lab, we will explore the fundamentals of JavaScript programming language. You will learn the basic syntax, data types, functions, and control structures of JavaScript. By the end of the lab, you will be able to write simple programs using JavaScript and have a solid understanding of the language. This lab is designed for beginners who have no prior experience in programming or JavaScript.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/AdvancedConceptsGroup(["`Advanced 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`") javascript/AdvancedConceptsGroup -.-> javascript/spread_rest("`Spread and Rest Operators`") subgraph Lab Skills javascript/variables -.-> lab-28389{{"`Index of Substrings`"}} javascript/data_types -.-> lab-28389{{"`Index of Substrings`"}} javascript/arith_ops -.-> lab-28389{{"`Index of Substrings`"}} javascript/comp_ops -.-> lab-28389{{"`Index of Substrings`"}} javascript/cond_stmts -.-> lab-28389{{"`Index of Substrings`"}} javascript/loops -.-> lab-28389{{"`Index of Substrings`"}} javascript/spread_rest -.-> lab-28389{{"`Index of Substrings`"}} end

Index of Substrings

To find all the indexes of a substring in a given string, follow these steps:

  1. Open the Terminal/SSH and type node to start practicing coding.
  2. Use the built-in method Array.prototype.indexOf() to search for searchValue in str.
  3. Use yield to return the index if the value is found and update the index, i.
  4. Use a while loop that will terminate the generator as soon as the value returned from Array.prototype.indexOf() is -1.

Here's an example code to implement the above steps:

const indexOfSubstrings = function* (str, searchValue) {
  let i = 0;
  while (true) {
    const r = str.indexOf(searchValue, i);
    if (r !== -1) {
      yield r;
      i = r + 1;
    } else return;
  }
};

You can test the function with the following code:

[...indexOfSubstrings("tiktok tok tok tik tok tik", "tik")]; // [0, 15, 23]
[...indexOfSubstrings("tutut tut tut", "tut")]; // [0, 2, 6, 10]
[...indexOfSubstrings("hello", "hi")]; // []

Summary

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

Other JavaScript Tutorials you may like