
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
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
Generate All Possible Combinations of a String in JavaScript
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