Go to Latest
method Buffer.prototype.lastIndexOf
import { Buffer } from "https://dotland.deno.dev/std@0.177.0/node/buffer.ts";

Identical to buf.indexOf(), except the last occurrence of value is found rather than the first occurrence.

import { Buffer } from 'buffer';

const buf = Buffer.from('this buffer is a buffer');

console.log(buf.lastIndexOf('this'));
// Prints: 0
console.log(buf.lastIndexOf('buffer'));
// Prints: 17
console.log(buf.lastIndexOf(Buffer.from('buffer')));
// Prints: 17
console.log(buf.lastIndexOf(97));
// Prints: 15 (97 is the decimal ASCII value for 'a')
console.log(buf.lastIndexOf(Buffer.from('yolo')));
// Prints: -1
console.log(buf.lastIndexOf('buffer', 5));
// Prints: 5
console.log(buf.lastIndexOf('buffer', 4));
// Prints: -1

const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'utf16le');

console.log(utf16Buffer.lastIndexOf('\u03a3', undefined, 'utf16le'));
// Prints: 6
console.log(utf16Buffer.lastIndexOf('\u03a3', -5, 'utf16le'));
// Prints: 4

If value is not a string, number, or Buffer, this method will throw aTypeError. 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. Any arguments that coerce to NaN, like {} or undefined, will search the whole buffer. This behavior matches String.prototype.lastIndexOf().

import { Buffer } from '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.lastIndexOf(99.9));
console.log(b.lastIndexOf(256 + 99));

// Passing a byteOffset that coerces to NaN.
// Prints: 1, searching the whole buffer.
console.log(b.lastIndexOf('b', undefined));
console.log(b.lastIndexOf('b', {}));

// Passing a byteOffset that coerces to 0.
// Prints: -1, equivalent to passing 0.
console.log(b.lastIndexOf('b', null));
console.log(b.lastIndexOf('b', []));

If value is an empty string or empty Buffer, byteOffset will be returned.

Parameters

value: string | number | Uint8Array

What to search for.

optional
byteOffset: number

Where to begin searching in buf. If negative, then offset is calculated from the end of buf.

optional
encoding: Encoding

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.

Returns

number

The index of the last occurrence of value in buf, or -1 if buf does not contain value.