Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Prodentim Probiotics Specially Designed For The Health Of Your Teeth And Gums

Instant Grammar Checker - Correct all grammar errors and enhance your writing

Teach Your Child To Read

Powerful WordPress hosting for WordPress professionals

Disclosure: My content contains affiliate links.

31,037 questions

40,846 answers

573 users

How to get all substrings of a string with JavaScript

2 Answers

0 votes
var s = "abcde";

for (var i = 0; i < s.length; i++) { 
    for (var j = i + 1; j <= s.length; j++) { 
         document.write(s.substring(i, j) + "<br />");
    }
}



/*

a
ab
abc
abcd
abcde
b
bc
bcd
bcde
c
cd
cde
d
de
e
    
*/

 





answered Oct 25, 2019 by avibootz
0 votes
function all_substrings(s) {
  var subs = [];

  for (var i = 0; i < s.length; i++) {
      for (var j = i + 1; j < s.length + 1; j++) {
          subs.push(s.slice(i, j));
      }
  }
  return subs;
}

var s = "abcde";

document.write(all_substrings(s));



/*

a,ab,abc,abcd,abcde,b,bc,bcd,bcde,c,cd,cde,d,de,e 
    
*/

 





answered Oct 25, 2019 by avibootz
...