Left Substring Generator

JavaScriptJavaScriptBeginner
Practice Now

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

Introduction

In this lab, we will explore how to generate all left substrings of a given string using JavaScript. We will create a leftSubstrGenerator function that uses a for...in loop and String.prototype.slice() to yield each substring of the given string, starting at the beginning. By the end of this lab, you will have a solid understanding of how to generate left substrings of any given string in 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/cond_stmts("`Conditional Statements`") javascript/BasicConceptsGroup -.-> javascript/loops("`Loops`") javascript/AdvancedConceptsGroup -.-> javascript/spread_rest("`Spread and Rest Operators`") subgraph Lab Skills javascript/variables -.-> lab-28468{{"`Left Substring Generator`"}} javascript/data_types -.-> lab-28468{{"`Left Substring Generator`"}} javascript/arith_ops -.-> lab-28468{{"`Left Substring Generator`"}} javascript/cond_stmts -.-> lab-28468{{"`Left Substring Generator`"}} javascript/loops -.-> lab-28468{{"`Left Substring Generator`"}} javascript/spread_rest -.-> lab-28468{{"`Left Substring Generator`"}} end

Code Practice: Left Substring Generator

To generate all left substrings of a given string, use the leftSubstrGenerator function provided below.

const leftSubstrGenerator = function* (str) {
  if (!str.length) return;
  for (let i in str) yield str.slice(0, i + 1);
};

To use the function, open the Terminal/SSH and type node. Then, enter the function with a string argument:

[...leftSubstrGenerator("hello")];
// [ 'h', 'he', 'hel', 'hell', 'hello' ]

The function uses String.prototype.length to terminate early if the string is empty and a for...in loop with String.prototype.slice() to yield each substring of the given string, starting at the beginning.

Summary

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

Other JavaScript Tutorials you may like