JavaScript 按给定数组元素分割字符串
假设我们给出了一个字符串和一个数组。我们的任务是根据数组的对应元素来分割字符串。例如 −
输入
const string = 'Javascript splitting string by given array element'; const arr = [2, 4, 5, 1, 3, 1, 2, 3, 7, 2];
输出
['Ja','vasc','ript ','s','pli','t','ti','ng ','string ','by']
让我们编写一个函数,称其 splitAtPosition ,其中包含字符串和数组,并且使用 Array.Prototype.reduce() 方法来返回分割后的数组。
此函数的代码为 −
Learn JavaScript in-depth with real-world projects through our JavaScript certification course. Enroll and become a certified expert to boost your career.
示例
const string = 'Javascript splitting string by given array element'; const arr = [2, 4, 5, 1, 3, 1, 2, 3, 7, 2]; const splitAtPosition = (str, arr) => { const newString = arr.reduce((acc, val) => { return { start: acc.start + val, newArr: acc.newArr.concat(str.substr(acc.start, val)) } }, { start: 0, newArr: [] }); return newString.newArr; }; console.log(splitAtPosition(string, arr));
输出
控制台中的输出为 −
[ 'Ja', 'vasc', 'ript ', 's', 'pli', 't', 'ti', 'ng ', 'string ', 'by' ]
广告