Home > front end >  Convert ASCII decimal to string
Convert ASCII decimal to string

Time:06-10

I have a string in representation of ASCII decimal stored in a column in my db:

[104 105]

this converts to hi.

I need to be able to convert my column into string representation.

I know I can use String.fromCharCode(num,...num 1) but it doesn't quite work for me.

I would need to parse and split my db column value [104 105] into two separate vars:

var num1 = 104;
var num2 - 105;

this doesn't work when I have a complex ASCII decimal representation.

Is there a more efficient way to do this? My input would be something like [104 105 243 0 0 255...] which is in ASCII decimal and I need to get the string representation.

CodePudding user response:

You need to parse that string first, by removing the [] characters, splitting at spaces, and converting the array elements to numbers.

let num_string = '[104 105]';
let nums = num_string.replace(/[\[\]]/g, '').split(' ').map(Number);
let string = String.fromCharCode(...nums);
console.log(string);

CodePudding user response:

You can find the codes using match with a regex, and then map and return an array of the converted codes. Just join the array into a string at the end.

function convert(str, re) {
  return str.match(/(\d )/g).map(code => {
    return String.fromCharCode(code);
  }).join('');
}

console.log(convert('[104 105]'));
console.log(convert('[104 105 243 0 0 255]'));

  • Related