w3resource

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:

Flowchart: JavaScript - Returns a subset of a string.

Live Demo:

See the Pen javascript-object-exercise-7 by w3resource (@w3resource) on CodePen.


For more Practice: Solve these Related Problems:

  • Write a JavaScript function that generates all non-empty substrings (subsets) of a given string.
  • Write a JavaScript function that returns all unique subsets of characters from a string using recursion.
  • Write a JavaScript function that generates subsets of a string while preserving the original order of characters.
  • Write a JavaScript function that excludes duplicate subsets when the input string contains repeating characters.

Go to:


PREV : Bubble Sort.
NEXT : Create Clock.

Improve this sample solution and post your code through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.