JavaScript 中無限擴充套件的字串中的子字串


我們需要編寫一個 JavaScript 函式,該函式接收一個字串作為第一個引數,將第二個引數作為開始索引,將第三個引數作為結束索引。該函式應查詢,如果將作為第一個引數提供的該字串無限擴充套件,每次都將相同的字串附加到其尾部,將用開始索引和結束索引封裝的子字串是什麼。

例如 −

如果輸入字串和索引是 −

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

則輸出應為 −

const output = 'hel';

示例

以下是程式碼 −

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));

輸出

以下是控制檯輸出 −

hel

更新於:23-01-2021

129 次瀏覽

開啟您的 職業 生涯

完成課程獲得認證

入門
廣告
© . All rights reserved.