Right Substring Generator

JavaScriptJavaScriptBeginner
Practice Now

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.


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/cond_stmts("`Conditional Statements`") javascript/BasicConceptsGroup -.-> javascript/loops("`Loops`") javascript/AdvancedConceptsGroup -.-> javascript/spread_rest("`Spread and Rest Operators`") subgraph Lab Skills javascript/variables -.-> lab-28604{{"`Right Substring Generator`"}} javascript/data_types -.-> lab-28604{{"`Right Substring Generator`"}} javascript/arith_ops -.-> lab-28604{{"`Right Substring Generator`"}} javascript/cond_stmts -.-> lab-28604{{"`Right Substring Generator`"}} javascript/loops -.-> lab-28604{{"`Right Substring Generator`"}} javascript/spread_rest -.-> lab-28604{{"`Right Substring Generator`"}} end

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.

Other JavaScript Tutorials you may like