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:
- Open the Terminal/SSH and type
nodeto start practicing coding. - Use
String.prototype.lengthto stop the iteration early if the string is empty. - Use a
for...inloop andString.prototype.slice()toyieldeach 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.