Create String from Ascii or Unicode - Node.js String

Node.js examples for String:Unicode

Description

Create String from Ascii or Unicode

Demo Code

String.fromAscii = function(data, start, end)
{
  start = start || 0;//from  w  w w. ja  va 2 s.c o m
  end = end || data.length;
  if (data instanceof Uint8Array || data instanceof Uint16Array)
  {
    var end1 = start;
    while (end1 < end && data[end1])
      end1++;
  
    return String.fromCharCode.apply(null, data.subarray(start, end1)).trim();
  }
  else
  {
    var result = "";
    for (; start < end; start++)
    {
      var c = data[start];
      if (c == 0)
        break;
      
      result += String.fromCharCode(c);
    }
    
    return result.trim();
  }
}

String.fromUnicode = function(data, endian, start, end)
{
  start = start || 0;
  end = (end || data.length) - 1;

  var result = "";
  var i1 = endian ? 0 : 1;
  var i2 = endian ? 1 : 0;
  for (; start < end; start += 2)
  {
    var c = data[start + i1] | (data[start + i2] << 8);
    if (c == 0)
      break;
    
    result += String.fromCharCode(c);
  }
  
  return result.trim();
}

Related Tutorials