Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

node.js
buffer
communitycreator

What is Buffer.lastIndexOf() method in node.js?

Gutha Vamsi Krishna

The lastIndexOf() method checks for the search term in the buffer object and returns it. If the search term occurs more than once in a buffer, it will return the position of the last occurrence.

Syntax

buffer.lastIndexOf(value, start, encoding);

Parameters

  • value: This is the search term that needs to be searched in the buffer.
  • start: This signals where to begin the search in the buffer. The default is 0.
  • encoding: If the search term is string, then this parameter is used to specify the encoding.

Return value

The lastIndexOf() method returns the last occurrence for given search term.

This method returns -1 if the search term is not found in the buffer.

Code

Example 1

In the example below:

  • We are trying to find the last index of i in the buf. Here, we have multiple occurrences of i: one is at index 2, and another is at index 5. So, the lastIndexOf method will return the last occurrence, that is index 5.
const buf = Buffer.from("This is an example")

//getting last index of i
console.log(buf.lastIndexOf('i'))

Example 2

In the example below:

  • We are trying to find z, which is not present in the buffer object buf, so the lastIndexOf method will return -1.
const buf = Buffer.from("This is an example")

//accessing the index of z which is not present in buffer
console.log(buf.lastIndexOf('z'))

RELATED TAGS

node.js
buffer
communitycreator
RELATED COURSES

View all Courses

Keep Exploring