Splicing string values using functions and loops a

2019-08-24 02:27发布

I have a list of numbers that is a string value using a loop I want to split this string into different variables in an array, the first of length 3 and the 6 of length 7 and the last of length 3. How can this be done using functions and loops.

this is the simple way I've done it, however I want to achieve the same outcome but using loops

4条回答
欢心
2楼-- · 2019-08-24 03:04

a generic way of doing this will be, if you want in a variable you can use subStringLengthMaps key, :-

let str="abcdefghijklmnopqrstu";
let  subStringLengthMap={a:3, b:7, c:7 , d:3};

//making pure funciton
var getStrings = function(str, subStringLengthMap){
  let result =[];
  Object.keys(subStringLengthMap).forEach(function(key){
  let temp = str.slice(0, subStringLengthMap[key]);
  result.push(temp);
    str = str.replace(temp,'');
  })

  return result;

}

//call the function
console.log(getStrings(str, subStringLengthMap))
查看更多
孤傲高冷的网名
3楼-- · 2019-08-24 03:06

Here's one way to do that:

let theArray = document.getElementById('theArray');
let theVariable = document.getElementById('theVariable');
let targetString = "122333444455555666666";
let dataSizes = [1, 2, 3, 4, 5, 6];
var result = [];
var pos = 0;
dataSizes.forEach( (size) => {
    result.push(targetString.substr(pos, size));
    pos += size;
});
theArray.textContent = result.toString();
let [one, two, three, four, five, six] = result;
theVariables.textContent = `${one}-${two}-${three}-${four}-${five}-${six}`;
查看更多
贼婆χ
4楼-- · 2019-08-24 03:18

You could map the sub strings.

var str = '000111111122222223333333444444455555556666666mmmm',
    lengths = [3, 7, 7, 7, 7, 7, 7, 3],
    result = lengths.map((i => l => str.slice(i, i += l))(0));

console.log(result);

查看更多
倾城 Initia
5楼-- · 2019-08-24 03:27

We could do something like this:

 
let str = '000111111122222223333333444444455555556666666mmmm';

// Defines the lengths we're using
let lengths = [3,7,7,7,7,7,7,3];

let index = 0;

let result = lengths.reduce((acc,n) => {
    acc.push(str.slice(index, index += n));
    return acc;
} , [])

console.log(result);

查看更多
登录 后发表回答