 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
JavaScript function that generates all possible combinations of a string
We are required to write a JavaScript function that takes in a string as the only argument. The function should generate an array of strings that contains all possible contiguous substrings that exist in the array.
Example
Following is the code −
const str = 'Delhi'; const allCombinations = (str1 = '') => {    const arr = [];    for (let x = 0, y=1; x < str1.length; x++,y++) {       arr[x]=str1.substring(x, y);    };    const combination = [];    let temp= "";    let len = Math.pow(2, arr.length);    for (let i = 0; i < len ; i++){       temp= "";       for (let j=0;j<arr.length;j++) {          if ((i & Math.pow(2,j))){             temp += arr[j];          }       };       if (temp !== ""){          combination.push(temp);       }    }    return combination; }; console.log(allCombinations(str));  Output
Following is the output on console −
[ 'D', 'e', 'De', 'l', 'Dl', 'el', 'Del', 'h', 'Dh', 'eh', 'Deh', 'lh', 'Dlh', 'elh', 'Delh', 'i', 'Di', 'ei', 'Dei', 'li', 'Dli', 'eli', 'Deli', 'hi', 'Dhi', 'ehi', 'Dehi', 'lhi', 'Dlhi', 'elhi', 'Delhi' ]
Advertisements
 