What is the Node.js Buffer.indexOf() method?
The indexOf() method will return the index of the value for the search term, if the search term is present in the buffer.
- If the search term is not found, then the method will return
-1. - If the search term is present more than once in the buffer, then it will return only the first occurrence.
Syntax
buffer.indexOf(value, start, encoding);
Parameters
Value: The search term that needs to be searched in the buffer.Start: Refers where to begin the search in the buffer. The default is0.Encoding: If thevalueis a string, then this parameter is used to specify the encoding. The default isutf8.
Example 1
In the following code snippet:
- In line 1, we will construct the buffer object with the fill as
Example bufferand store the buffer object in variablebuf. - In line 2, we will get the index of the
buffertext from buffer stringbuf, with thebuf.indexOf('buffer')method and print it in the console.
const buf = Buffer.from('Example buffer')console.log("Index of buffer is "+ buf.indexOf('buffer'))
Example 2
In the following code snippet:
- In line 1, we will construct the buffer object with the fill as
Example bufferand store the buffer object in variablebuf. - In line 4, we will get the index of character
ein the buffer objectbufand print it in the console.
If the search term is present more than once in the buffer, then it will return only the first occurrence.
const buf = Buffer.from('Example buffer')//here e has multiple occurrences but returns only first occurrenceconsole.log("Index of e is "+ buf.indexOf('e'))
Example 3
In the following code snippet:
- In line 1, we will construct the buffer object with fill as
Example bufferand store the buffer object in the variablebuf. - In line 4, we will get the index of character
zin buffer objectbuf, with thebuf.indexOf('z')method and print it in the console.
If the search term is not found, then the method will return
-1.
const buf = Buffer.from('Example buffer')//returns -1 as z is not present in the bufferconsole.log("Index of z is "+ buf.indexOf('z'))