Substring combination in JavaScript

JavascriptWeb DevelopmentFront End Technology

We are required to write a JavaScript function that takes in two strings as the first and the second argument. Let's call these strings str1 and str2. The function should check whether there exists a substring combination in str2, that when combined yields str2.

By substring combination, we mean that we can skip characters but we have to maintain the order of the characters selected from str1.

For example −

If the input strings are −

const str1 = 'desxooajmepwele';
const str2 = 'example';

Then the output should be −

const output = true;

because the string 'example' can be formed by picking some and maintianing the order of characters from str1.


The code for this will be −

 Live Demo

const str1 = 'desxooajmepwele';
const str2 = 'example';
const containsString = (str1 = '', str2 = '') => {
   let [foundAt, next] = [0, 0];
   for(const char of str2){
      next = str1.slice(foundAt).indexOf(char);
      if (next === - 1){
         return false;
      foundAt += next + 1;
   return true;
console.log(containsString(str1, str2));


And the output in the console will be −

Updated on 24-Feb-2021 16:12:50