Right Substring Generator

Beginner

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

Introduction

In this lab, we will be exploring the concept of substring generation in JavaScript. We will focus on generating right substrings of a given string using the for...in loop and String.prototype.slice() method. By the end of this lab, you will have a better understanding of how to manipulate strings in JavaScript and generate substrings for various use cases.

Right Substring Generator

To generate all right substrings of a given string, follow these steps:

  1. Open the Terminal/SSH and type node to start practicing coding.
  2. Use String.prototype.length to stop the iteration early if the string is empty.
  3. Use a for...in loop and String.prototype.slice() to yield each substring of the given string, starting from the end.

Here's the code snippet:

const rightSubstrGenerator = function* (str) {
  if (!str.length) return;
  for (let i in str) yield str.slice(-i - 1);
};

Example usage:

[...rightSubstrGenerator("hello")];
// [ 'o', 'lo', 'llo', 'ello', 'hello' ]

Summary

Congratulations! You have completed the Right Substring Generator lab. You can practice more labs in LabEx to improve your skills.