Alex
Alex

Reputation: 33

How to create array from number, based on digits number in JS?

I need to translate ASCII code in HEX to characters. I got from server numbers(as string) in ascii, like: 64656661756c74 (which means 'default'). I know about String.fromCharCode(), but first i need to split the raw message to 2-digits pieces(array). How can i split 2-digits-duration based? Thanks.

Upvotes: 2

Views: 131

Answers (4)

Kosh
Kosh

Reputation: 18393

Using replace:

let a = '64656661756c74';

let r = a.replace(/([0-9a-f]{2})/g, (m, a) => String.fromCharCode(parseInt(a, 16)))

console.log(r)

Oldschool approach:

let a = '64656661756c74', r = '';

for (let i = 0; i < a.length; i+=2)
  r += String.fromCharCode(parseInt(a.substring(i, i+2), 16))

console.log(r)

Upvotes: 2

Abdullah Leghari
Abdullah Leghari

Reputation: 2470

As noted in comments above, your ASCII sequence is probably incorrect. Maybe it is a hexadecimal stream.

Assuming the correct ASCII numbers, you can go as following,

var str = '68697065857684';
str = str.match(/.{1,2}/g);


for (index = str.length - 1; index >= 0; --index) {
  var temp = str[index];  
  str[index]= String.fromCharCode(temp);
}

console.log(str);

Upvotes: 0

ZER0
ZER0

Reputation: 25322

Since the string is hex string representation, you have also to convert in decimal number before you pass to String.fromCharCode:

const str = "64656661756c74"
              .match(/.{2}/g)
              .map(ch => String.fromCharCode(parseInt(ch, 16)))
              .join("");
              
console.log(str);
// "default"

That basically store in str the value "default", as you said.

Upvotes: 4

Jack Bashford
Jack Bashford

Reputation: 44125

To split that into 2-character chunks, use a regular expression like so:

var str = '64656661756c74';
str = str.match(/.{1,2}/g);
console.log(str);

Upvotes: 1

Related Questions