buffer.indexOf()

buf.indexOf(value[, byteOffset][, encoding])

Operates similar to Array#indexOf() in that it returns either the starting index position of value in Buffer or -1 if the Buffer does not contain value. The value can be a String, Buffer or Number. Strings are by default interpreted as UTF8. Buffers will use the entire Buffer (to compare a partial Buffer use buf.slice()). Numbers can range from 0 to 255.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
const buf = Buffer.from('this is a buffer');
 
buf.indexOf('this');
  // returns 0
buf.indexOf('is');
  // returns 2
buf.indexOf(Buffer.from('a buffer'));
  // returns 8
buf.indexOf(97); // ascii for 'a'
  // returns 8
buf.indexOf(Buffer.from('a buffer example'));
  // returns -1
buf.indexOf(Buffer.from('a buffer example').slice(0,8));
  // returns 8
 
const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'ucs2');
 
utf16Buffer.indexOf('\u03a3',  0, 'ucs2');
  // returns 4
utf16Buffer.indexOf('\u03a3', -4, 'ucs2');
  // returns 6
doc_Nodejs
2025-01-10 15:47:30
Comments
Leave a Comment

Please login to continue.