I would use an array

@Pipe({ name: 'titleCase'})
class TitleCasePipe extends PipeTransform {
  transform(value:string, args:any[] ):any {
    buffer:string[] = [];

    if ( !isNull( value ) ) {
      list:string[] = value.split( '' );


      if ( value.match(/^[is]{1,2}([A-Z]|[0-9]).*/ ) ) {
        start:number = 2;
        sublist:string[] = list.slice( start );
        return sublist.join( '' );
      }

      for (i = 0; i < list.length; i++ ) {
        if ( i == 0 ) {
          buffer.push( list[i].toUpperCase( ) );
          continue;
        }

        if ( isUppercase( list[i] ) ) {
          buffer.push( ' ' );
          buffer.push( list[i] );
          continue;
        }

        buffer.push( list[i] );
      }
    }
    return buffer.join('');
  }
}

(caution - not tested)

Answer from Günter Zöchbauer on Stack Overflow
🌐
W3Schools
w3schools.com › nodejs › met_buffer_tostring.asp
Node.js buffer toString() Method
The toString() method returns the buffer object according to the specified encoding.
Discussions

Assigning Buffer to string issue

"utf8" should be given as an argument to fs.readFileSync, but you have it as an argument to path.join. Do this instead:

const configDataRaw = fs.readFileSync(
  path.join(__dirname, "../../../configuration.json"),
  "utf8"
);

Providing an encoding argument to readFileSync (in this case the encoding is "utf8") causes TypeScript to apply an overloaded signature of readFileSync where the return type is string instead of Buffer. At runtime the encoding argument causes Node to convert the file content buffer to a string for you automatically.

More on reddit.com
🌐 r/typescript
3
4
June 23, 2020
node.js - Convert string to buffer Node - Stack Overflow
I am using a library which on call of a function returns the toString of a buffer. ... But I don't want string version of it. More on stackoverflow.com
🌐 stackoverflow.com
convert Buffer to String - javascript
Communities for your favorite technologies. Explore all Collectives · Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work More on stackoverflow.com
🌐 stackoverflow.com
Nodejs: convert string to buffer - javascript
I'm trying to write a string to a socket (socket is called "response"). Here is the code I have sofar (I'm trying to implement a byte caching proxy...): var http = require('http'); var sys=require... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Webdevtutor
webdevtutor.net › blog › typescript-buffer-from-string
A Comprehensive Guide to Creating TypeScript Buffer from String
To convert a string into a buffer in TypeScript, you can use the Buffer.from() method. This method takes the string as input and returns a buffer containing the string's binary representation.
🌐
Reddit
reddit.com › r/typescript › assigning buffer to string issue
r/typescript on Reddit: Assigning Buffer to string issue
June 23, 2020 -
// doesn't work
      const configDataRaw = fs.readFileSync(
         path.join(__dirname, "../../../configuration.json", "utf8")
      );

      const configData = JSON.parse(configDataRaw);
// const configDataRaw: Buffer
// Argument of type 'Buffer' is not assignable to parameter of type 'string'.ts(2345)

// works
      const configData2 = JSON.parse(path.join(__dirname, 
        "../../../configuration.json", "utf8")
      );

All of the following failed:

 const configDataRaw as string = fs.readFileSync(

 const configDataRaw<string> = fs.readFileSync(


      const configData = JSON.parse((configDataRaw as string));

      const configData = JSON.parse(configDataRaw<string>);

What is the correct way to assert this is not a buffer, but a string?

In the first code block, code sample #2, it seems to infer properly, I don't understand why the more iterative version acts differently here.

🌐
Webdevtutor
webdevtutor.net › blog › typescript-create-buffer-from-string
How to Create Buffer from String in TypeScript
One simple and efficient way to create a buffer from a string in TypeScript is by using the Buffer.from() method.
🌐
Webdevtutor
webdevtutor.net › blog › typescript-string-to-buffer
Converting TypeScript Strings to Buffers: A Guide
In this example, we create a new Buffer object from our input string using the from() method. Another way to convert a TypeScript string to a buffer is by using the Uint8Array class.
🌐
Melvin George
melvingeorge.me › blog › convert-string-buffer-nodejs
How to convert a String to Buffer and vice versa in Node.js | MELVIN GEORGE
September 19, 2020 - // a string const str = "Hey. this is a string!"; // convert string to Buffer const buff = Buffer.from(str, "utf-8"); console.log(buff); // <Buffer 48 65 79 2e ...
Find elsewhere
🌐
Index.dev
index.dev › blog › json-to-buffer-typescript
Convert JSON to Buffer in TypeScript: A Step-by-Step Guide
With our JSON string now in hand, we can turn it into a buffer. For this, TypeScript has the Buffer.from() function, which is compatible with Node.js.
🌐
Node.js
nodejs.org › api › buffer.html
Buffer | Node.js v26.10.0 Documentation
Node.js also supports the following binary-to-text encodings. For binary-to-text encodings, the naming convention is reversed: Converting a Buffer into a string is typically referred to as encoding, and converting a string into a Buffer as decoding.
🌐
Webdevtutor
webdevtutor.net › blog › typescript-string-to-arraybuffer
Converting TypeScript Strings to ArrayBuffer: A Comprehensive Guide
In this example, we create a ... the binary representation of the input string. The second approach involves using the Uint16Array constructor to create an array buffer from a string....
🌐
DEV Community
dev.to › melvin2016 › how-to-convert-a-string-to-buffer-and-vice-versa-in-node-js-5op
How to convert a String to Buffer and vice versa in Node.js - DEV Community
September 19, 2020 - To convert a string to a Buffer, you can use the from() method from the global Buffer class in Node.js.
🌐
Wanago
wanago.io › home › node.js typescript #3. explaining the buffer
Node.js TypeScript #3. Explaining buffers - wanago.io
February 25, 2019 - Since Buffers store byte data, you can also use it to operate on strings.
🌐
Medium
medium.com › @ryan_forrester_ › buffer-to-string-in-javascript-how-to-guide-b24027575419
Buffer to String in JavaScript (How To Guide) | by ryan | Medium
January 7, 2025 - A buffer is created from a string using Buffer.from. The buffer is then converted back to a string using the toString method.
🌐
Webdevtutor
webdevtutor.net › blog › typescript-buffer-string
Understanding TypeScript Buffer String: A Comprehensive Guide
Understanding how to work with Buffers and Strings in TypeScript is crucial for efficient data manipulation. By leveraging the capabilities of Buffers for binary data and Strings for text data, you can enhance the performance and reliability of your TypeScript applications.
Top answer
1 of 16
352

Update 2016 - five years on there are now new methods in the specs (see support below) to convert between strings and typed arrays using proper encoding.

##TextEncoder

The TextEncoder represents:

The TextEncoder interface represents an encoder for a specific method, that is a specific character encoding, liarraybufferke utf-8, iso-8859-2, koi8, cp1261, gbk, ... An encoder takes a stream of code points as input and emits a stream of bytes.

Change note since the above was written: (ibid.)

Note: Firefox, Chrome and Opera used to have support for encoding types other than utf-8 (such as utf-16, iso-8859-2, koi8, cp1261, and gbk). As of Firefox 48 [...], Chrome 54 [...] and Opera 41, no other encoding types are available other than utf-8, in order to match the spec.*

*) Updated specs (W3) and here (whatwg).

After creating an instance of the TextEncoder it will take a string and encode it using a given encoding parameter:

if (!("TextEncoder" in window)) 
  alert("Sorry, this browser does not support TextEncoder...");

var enc = new TextEncoder(); // always utf-8
console.log(enc.encode("This is a a string to be converted to a Uint8Array"));
Run code snippetEdit code snippet Hide Results Copy to answer Expand

You then of course use the .buffer parameter on the resulting Uint8Array to convert the underlaying ArrayBuffer to a different view if needed.

Just make sure that the characters in the string adhere to the encoding schema, for example, if you use characters outside the UTF-8 range in the example they will be encoded to two bytes instead of one.

For general use you would use UTF-16 encoding for things like localStorage.

##TextDecoder

Likewise, the opposite process uses the TextDecoder:

The TextDecoder interface represents a decoder for a specific method, that is a specific character encoding, like utf-8, iso-8859-2, koi8, cp1261, gbk, ... A decoder takes a stream of bytes as input and emits a stream of code points.

All available decoding types can be found here.

if (!("TextDecoder" in window))
  alert("Sorry, this browser does not support TextDecoder...");

var enc = new TextDecoder("utf-8");
var arr = new Uint8Array([84,104,105,115,32,105,115,32,97,32,85,105,110,116,
                          56,65,114,114,97,121,32,99,111,110,118,101,114,116,
                          101,100,32,116,111,32,97,32,115,116,114,105,110,103]);
console.log(enc.decode(arr));
Run code snippetEdit code snippet Hide Results Copy to answer Expand

##The MDN StringView library

An alternative to these is to use the StringView library (licensed as lgpl-3.0) which goal is:

  • to create a C-like interface for strings (i.e., an array of character codes — an ArrayBufferView in JavaScript) based upon the JavaScript ArrayBuffer interface
  • to create a highly extensible library that anyone can extend by adding methods to the object StringView.prototype
  • to create a collection of methods for such string-like objects (since now: stringViews) which work strictly on arrays of numbers rather than on creating new immutable JavaScript strings
  • to work with Unicode encodings other than JavaScript's default UTF-16 DOMStrings

giving much more flexibility. However, it would require us to link to or embed this library while TextEncoder/TextDecoder is being built-in in modern browsers.

#Support

As of July/2018:

TextEncoder (Experimental, On Standard Track)

 Chrome    | Edge      | Firefox   | IE        | Opera     | Safari
 ----------|-----------|-----------|-----------|-----------|-----------
     38    |     ?     |    19°    |     -     |     25    |     -

 Chrome/A  | Edge/mob  | Firefox/A | Opera/A   |Safari/iOS | Webview/A
 ----------|-----------|-----------|-----------|-----------|-----------
     38    |     ?     |    19°    |     ?     |     -     |     38

°) 18: Firefox 18 implemented an earlier and slightly different version
of the specification.

WEB WORKER SUPPORT:

Experimental, On Standard Track

 Chrome    | Edge      | Firefox   | IE        | Opera     | Safari
 ----------|-----------|-----------|-----------|-----------|-----------
     38    |     ?     |     20    |     -     |     25    |     -

 Chrome/A  | Edge/mob  | Firefox/A | Opera/A   |Safari/iOS | Webview/A
 ----------|-----------|-----------|-----------|-----------|-----------
     38    |     ?     |     20    |     ?     |     -     |     38

Data from MDN - `npm i -g mdncomp` by epistemex
2 of 16
207

Although Dennis and gengkev solutions of using Blob/FileReader work, I wouldn't suggest taking that approach. It is an async approach to a simple problem, and it is much slower than a direct solution. I've made a post in html5rocks with a simpler and (much faster) solution: http://updates.html5rocks.com/2012/06/How-to-convert-ArrayBuffer-to-and-from-String

And the solution is:

function ab2str(buf) {
  return String.fromCharCode.apply(null, new Uint16Array(buf));
}

function str2ab(str) {
  var buf = new ArrayBuffer(str.length*2); // 2 bytes for each char
  var bufView = new Uint16Array(buf);
  for (var i=0, strLen=str.length; i<strLen; i++) {
    bufView[i] = str.charCodeAt(i);
  }
  return buf;
}

EDIT:

The Encoding API helps solving the string conversion problem. Check out the response from Jeff Posnik on Html5Rocks.com to the above original article.

Excerpt:

The Encoding API makes it simple to translate between raw bytes and native JavaScript strings, regardless of which of the many standard encodings you need to work with.

<pre id="results"></pre>

<script>
  if ('TextDecoder' in window) {
    // The local files to be fetched, mapped to the encoding that they're using.
    var filesToEncoding = {
      'utf8.bin': 'utf-8',
      'utf16le.bin': 'utf-16le',
      'macintosh.bin': 'macintosh'
    };

    Object.keys(filesToEncoding).forEach(function(file) {
      fetchAndDecode(file, filesToEncoding[file]);
    });
  } else {
    document.querySelector('#results').textContent = 'Your browser does not support the Encoding API.'
  }

  // Use XHR to fetch `file` and interpret its contents as being encoded with `encoding`.
  function fetchAndDecode(file, encoding) {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', file);
    // Using 'arraybuffer' as the responseType ensures that the raw data is returned,
    // rather than letting XMLHttpRequest decode the data first.
    xhr.responseType = 'arraybuffer';
    xhr.onload = function() {
      if (this.status == 200) {
        // The decode() method takes a DataView as a parameter, which is a wrapper on top of the ArrayBuffer.
        var dataView = new DataView(this.response);
        // The TextDecoder interface is documented at http://encoding.spec.whatwg.org/#interface-textdecoder
        var decoder = new TextDecoder(encoding);
        var decodedString = decoder.decode(dataView);
        // Add the decoded file's text to the <pre> element on the page.
        document.querySelector('#results').textContent += decodedString + '\n';
      } else {
        console.error('Error while requesting', file, this);
      }
    };
    xhr.send();
  }
</script>
🌐
DigitalOcean
digitalocean.com › community › tutorials › using-buffers-in-node-js
Using Buffers in Node.js | DigitalOcean
May 1, 2020 - To access one byte of a buffer, we pass the index or location of the byte we want. Buffers store data sequentially like arrays. They also index their data like arrays, starting at 0. We can use array notation on the buffer object to get an individual byte. Let’s see how this looks by creating a buffer from a string in the REPL: