简体   繁体   English

javascript 按第一个长度分割字符串

[英]javascript to split string by first of length

I have a string like this "1a8abder412183a2b9654123879"我有一个像这样的字符串"1a8abder412183a2b9654123879"

How can I split the string by length of first char like this using javascript如何使用 javascript 像这样按第一个字符的长度拆分字符串

1 -> a,
8 -> abder412,
3 -> a2b,
9 -> 654123879,

Assuming only length of 1 to 9, then you could get the length from the actual index and slice the array by taking the index plus expected length.假设只有 1 到 9 的长度,那么您可以从实际索引中获取长度,并通过获取索引加上预期长度来对数组进行切片。 Proceed until no more string si left.继续直到没有更多的字符串 si 离开。

 var string = '1a8abder412183a2b9654123879', result = [], index = 0, length; while (index < string.length) result.push([length = +string[index++], string.slice(index, index += length)]); console.log(result);
 .as-console-wrapper { max-height: 100%;important: top; 0; }

 let input = '1a8abder412183a2b9654123879'; let keys = [1, 8, 3, 9]; let splitByKeys = (input, keys) => { let lastIndex = input.indexOf(keys[0]); let splits = []; for (let i = 1; i <= keys.length; i++) { let index = i < keys.length? input.indexOf(keys[i], lastIndex): input.length; let m = input.substring(lastIndex + 1, index); lastIndex = index; splits.push([keys[i - 1], m]); } return Object.fromEntries(splits); } let output = splitByKeys(input, keys); console.log(output);

 const str = "1a8abder412183a2b9654123879"; const chunks = (arr, acc = []) => { return (arr.length === 0)? acc: chunks( arr.slice(parseInt(arr[0])+1), [...acc, arr.slice(0, parseInt(arr[0]) + 1).join('')] ); } console.log(chunks([...str]));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM