Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
444 views
in Technique[技术] by (71.8m points)

javascript - 将JavaScript字符串拆分为不同长度的片段(Split a JavaScript string into pieces of different length)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use a combination of String.prototype.substring() and Array.prototype.slice()(结合使用String.prototype.substring()Array.prototype.slice())

const lengths = [4, 1, 6] const string = "some string" const parts = lengths.map((len, i) => { let prevLen; if (i === 0) { prevLen = 0 } else { prevLen = lengths.slice(0, i).reduce((sum, l) => sum + l, 0) } return string.substring(prevLen, len + prevLen) }) console.log(parts);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...