snippetjavascriptTip
How can I generate all partial substrings of a string in JavaScript?
Viewed 0 times
javascriptpartialhowallgeneratecansubstringsstring
Problem
Sometimes, you might need to generate all partial substrings of a string. This might come in handy in a variety of situations, such as string matching, or string compression. Luckily, using JavaScript's generator functions, this is a fairly simple task.
Using a
The exact same technique with a
Using a
for...in loop, we can iterate over the string, and yield each substring, starting at the beginning. We can use String.prototype.slice() to get the substring. In order to terminate early, we can use String.prototype.length to check if the string is empty.The exact same technique with a
for...in loop can be used when starting at the end of the string. Same as before, albeit with a slight modification, we can use String.prototype.slice() to get the substring. And again, we use String.prototype.length to terminate early if the string is empty.Solution
const leftSubstrGenerator = function* (str) {
if (!str.length) return;
for (let i in str) yield str.slice(0, i + 1);
};
[...leftSubstrGenerator('hello')];
// [ 'h', 'he', 'hel', 'hell', 'hello' ]The exact same technique with a
for...in loop can be used when starting at the end of the string. Same as before, albeit with a slight modification, we can use String.prototype.slice() to get the substring. And again, we use String.prototype.length to terminate early if the string is empty.Code Snippets
const leftSubstrGenerator = function* (str) {
if (!str.length) return;
for (let i in str) yield str.slice(0, i + 1);
};
[...leftSubstrGenerator('hello')];
// [ 'h', 'he', 'hel', 'hell', 'hello' ]const rightSubstrGenerator = function* (str) {
if (!str.length) return;
for (let i in str) yield str.slice(-i - 1);
};
[...rightSubstrGenerator('hello')];
// [ 'o', 'lo', 'llo', 'ello', 'hello' ]Context
From 30-seconds-of-code: substring-generator
Revisions (0)
No revisions yet.