Skip to content Skip to sidebar Skip to footer

Splicing String Values Using Functions And Loops And Storing As An Array

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 l

Solution 1:

We could do something like this:

let str = '000111111122222223333333444444455555556666666mmmm';

// Defines the lengths we're usinglet 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);

Solution 2:

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);

Solution 3:

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}`;

Solution 4:

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 funcitonvar 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 functionconsole.log(getStrings(str, subStringLengthMap))

Post a Comment for "Splicing String Values Using Functions And Loops And Storing As An Array"