indexOf
If value
is:
a string,
value
is interpreted according to the character encoding inencoding
.a
Buffer
orUint8Array
,value
will be used in its entirety. To compare a partialBuffer
, usebuf.subarray
.a number,
value
will be interpreted as an unsigned 8-bit integer value between0
and255
.
import { Buffer } from 'node:buffer';
const buf = Buffer.from('this is a buffer');
console.log(buf.indexOf('this'));
// Prints: 0
console.log(buf.indexOf('is'));
// Prints: 2
console.log(buf.indexOf(Buffer.from('a buffer')));
// Prints: 8
console.log(buf.indexOf(97));
// Prints: 8 (97 is the decimal ASCII value for 'a')
console.log(buf.indexOf(Buffer.from('a buffer example')));
// Prints: -1
console.log(buf.indexOf(Buffer.from('a buffer example').slice(0, 8)));
// Prints: 8
const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'utf16le');
console.log(utf16Buffer.indexOf('\u03a3', 0, 'utf16le'));
// Prints: 4
console.log(utf16Buffer.indexOf('\u03a3', -4, 'utf16le'));
// Prints: 6
If value
is not a string, number, or Buffer
, this method will throw a TypeError
. If value
is a number, it will be coerced to a valid byte value, an integer between 0 and 255.
If byteOffset
is not a number, it will be coerced to a number. If the result of coercion is NaN
or 0
, then the entire buffer will be searched. This behavior matches String.prototype.indexOf()
.
import { Buffer } from 'node:buffer';
const b = Buffer.from('abcdef');
// Passing a value that's a number, but not a valid byte.
// Prints: 2, equivalent to searching for 99 or 'c'.
console.log(b.indexOf(99.9));
console.log(b.indexOf(256 + 99));
// Passing a byteOffset that coerces to NaN or 0.
// Prints: 1, searching the whole buffer.
console.log(b.indexOf('b', undefined));
console.log(b.indexOf('b', {}));
console.log(b.indexOf('b', null));
console.log(b.indexOf('b', []));
If value
is an empty string or empty Buffer
and byteOffset
is less than buf.length
, byteOffset
will be returned. If value
is empty andbyteOffset
is at least buf.length
, buf.length
will be returned.
Since
v1.5.0
Return
The index of the first occurrence of value
in buf
, or -1
if buf
does not contain value
.
Parameters
What to search for.
encoding='utf8' If value
is a string, this is the encoding used to determine the binary representation of the string that will be searched for in buf
.