Egidi
Egidi

Reputation: 1776

Javascript split string in different sized substrings

I need to code an algo that, giving a hex string,generates an array with 5 elements of 4 hex digits and another array with 2 elemetents of 2 hex digits long. The unique two premises are:

Example of one correct output:

String : 87b86156d0000a4200005e02002f56614f7a2f54f7ebf45670ed62cbaa78e6f228297b0e7338215fb4

first array: ["87b8", "6156", "d000", "0a42", "5e02"]

second array: ["2f", "56"]

My approach starts like this:

var mystring = "87b86156d0970a4200005e02612f56614f7a2f54f7ebf45670ed62cbaa78e6f228297b0e7338215fb4"
var firststring = mystring.match(/.{1,4}/g);

Which gives me:

["87b8", "6156", "d097", "0a42", "0000", ...]

then:

for (x=0;x<firststring.length;x++){
        if (firststring[x]=="0000") {firststring.splice(x, 1)}
}

  var secondstring = mystring.match(/.{1,2}/g);

Which gives me:

["87", "b8", "61", "56", "d0", "97"...]

for (x=0;x<secondstring.length;x++){
        if (secondstring[x]=="00") {secondstring.splice(x, 1)}
}

Here is where i am lost, i don't know exactly how to code the part where i avoid the main string digits (positions) to be used in both arrays...

Regards,

Upvotes: 1

Views: 189

Answers (1)

jmar777
jmar777

Reputation: 39649

Well, it's not pretty, but it works:

var str = "87b86156d0970a4200005e02612f56614f7a2f54f7ebf45670ed62cbaa78e6f228297b0e7338215fb4";

var grabLength = 4,
    // 4-char strings
    grp1 = [],
    // 2-char strings
    grp2 = [],
    chunk;

while(chunk = str.slice(0, grabLength)) {
  str = str.slice(grabLength);

  // skip all zeros
  if (/^0+$/.test(chunk)) continue;

  if (grabLength === 4) {
    if (grp1.push(chunk) === 5) {
      grabLength = 2;
    }
    continue;
  }

  // skip 2-char sequences that match the start of a 4-char sequence
  var hasMatch = false;
  for (var i = 0; i < grp1.length; i++) {
    if (chunk === grp1[i].slice(0, 2)) {
      hasMatch = true;
      continue;
    }
  }
  if (hasMatch) continue;

  grp2.push(chunk);

  if (grp2.length === 2) break;
}

console.log(grp1);
console.log(grp2);

JSBin

Upvotes: 1

Related Questions