skip to Main Content

I am trying to split a hexadecimal string, 3E8.8F5C28F5C28, into individual bytes. I tried the following code to split the string:

const string = "3E8.8F5C28F5C28";
const res = string.split(/([dw]{2})/).filter(e => e);

But it gave me this result:

[
  '3E', '8.', '8F',
  '5C', '28', 'F5',
  'C2', '8'
]

I need to split the given hex string like 03 E8 8F. I don’t want the fractional values after 8F.

How to achieve this?

2

Answers


  1. It’s an easy task do it like this:

    const string = "3E8.8F5C28F5C28";
    // Remove the fractional part
    const sanitizedString = string.split(".")[0];
    const result = sanitizedString.padStart(sanitizedString.length + (sanitizedString.length % 2), '0').match(/.{1,2}/g) || [];
    console.log(result);
    
    Login or Signup to reply.
  2. You could first pad the string so it has an even number of hex digits in both the integer as fractional parts. Then clip the fractional part to just 2 digits, and finally match all digit pairs.

    const string = "3E8.8F5C28F5C28";
    const res = string
         .replace(/(ww)*wb/, "0$&")  // Pad integer part  
         .replace(/b(ww)*w$/, "$&0") // Pad fractional part
         .replace(/(.ww).*/, "$1")    // Keep at most 2 decimals
         .match(/ww/g);                // Get hex pairs
         
    console.log(res);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search