Substring in infinitely extended string in JavaScript

JavascriptWeb DevelopmentFront End Technology

We are required to write a JavaScript function that takes in a string of characters as the first argument and a start index and end index as second and third argument respectively. The function should find, had that string, provided as the first argument, been extended forever by appending the same string at end each time, what would have been the substring encapsulated by the start index and the end index.

For example −

If the input string and the indices are −

const str = 'helloo';
const start = 11;
const end = 15;

Then the output should be −

const output = 'hel';

Example

Following is the code −

const str = 'helloo';
const start = 12;
const end = 15;
const findSubstring = (str = '', start, end) => {
   let n = str.length;
   let t = start / n;
   start = start % n;
   end -= t * n;
   let res = str.substring(start, end - start);
   if (end > n){
      t = (end - n) / n;
      end = (end - n) - t * n;
      while (t --) {
         res += str;
      }
      res += str.substring(0, end);
   };
   return res;
};
console.log(findSubstring(str, start, end));

Output

Following is the console output −

hel
raja
Published on 23-Jan-2021 06:31:40
Advertisements