To get all possible K length substrings of a string in JavaScript, you can use nested loops to iterate through each possible substring.
In this example,
str
with a value of 'Hello World'
.substrings
to store all substrings of length 3.substring
method and push it to the substrings
array.substrings
array to the console.let str = 'Hello World';
let k = 3;
let substrings = [];
for (let i = 0; i <= str.length - k; i++) {
for (let j = i; j < i + k; j++) {
substrings.push(str.substring(i, j + 1));
}
}
console.log(`All substrings of length ${k}:`, substrings);
All substrings of length 3: [ 'H', 'He', 'Hel', 'e', 'el', 'ell', 'l', 'll', 'llo', 'l', 'lo', 'lo ', 'o', 'o ', 'o W', ' ', ' W', ' Wo', 'W', 'Wo', 'Wor', 'o', 'or', 'orl', 'r', 'rl', 'rld' ]
In this tutorial, we learned How to get all the possible K length Substrings in a String in JavaScript language with well detailed examples.