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' ]
Updated on: 2020-12-11T09:45:26+05:30

799 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements