I tried to play with match(/.{1,n}/g);
(我试图玩match(/.{1,n}/g);
)
, but I cant't reproduce expected result.(,但我无法重现预期的结果。)
Input: const str = "some string"; const lengths = [4,1,6]
(输入: const str = "some string"; const lengths = [4,1,6]
) const str = "some string"; const lengths = [4,1,6]
Output: ['some', '', 'string']
(输出: ['some', '', 'string']
)
A solution:(一个办法:)
const string = ' 1234567'
const lengths = [4, 2, -1, -3, 2]
const getSubStrArrByLengthsArr = (lengthArr, str) => {
const results = []
for(let i = 0, j = 0; i < lengthArr.length; i++) {
if(j >= str.length || lengthArr[i] > str.length) return results;
if(lengthArr[i] > 0) {
results.push(str.substr(j, lengthArr[i]))
j += lengthArr[i]
}
}
return results;
}
console.log(getSubStrArrByLengthsArr(lengths, string)) // [' ', ' ', '12']
ask by Vladislav Pokosenko translate from so
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…