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