JavaScript: Returns a subset of a string
JavaScript Object: Exercise-7 with Solution
String Subsets
Write a JavaScript program that returns a subset of a string.
Sample Data: dog
Expected Output: ["d", "do", "dog", "o", "og", "g"]
Sample Solution:
JavaScript Code:
String.prototype.sub_String = function()
{
var subset = [];
for (var m = 0; m < this.length; m++)
{
for (var n = m+1; n<this.length+1; n++)
{
subset.push(this.slice(m,n));
}
}
return subset;
};
console.log("dog".sub_String());
Output:
["d","do","dog","o","og","g"]
Flowchart:
Live Demo:
See the Pen javascript-object-exercise-7 by w3resource (@w3resource) on CodePen.
Improve this sample solution and post your code through Disqus.
Previous: Write a Bubble Sort algorithm in JavaScript.
Next: Write a JavaScript program to create a Clock.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics