Find positions in JavaScript strings with indexOf() and lastIndexOf()

indexOf() returns the starting index of the first match in a JavaScript string. lastIndexOf() returns the starting index of the last match. Indexes start at zero. Both methods return -1 if there is no match and distinguish uppercase from lowercase.

Find the first and last match

const text = 'banana';
console.log(text.indexOf('ana'));     // 1
console.log(text.lastIndexOf('ana')); // 3
console.log(text.indexOf('ANA'));     // -1
console.log(text.indexOf('b'));       // 0

Compare the result with -1. A truthiness check treats a match at index 0 as false and a result of -1 as true. Use includes() when you only need to know whether the query occurs. See indexOf() and lastIndexOf().

Set a starting position in each direction

The second argument sets the earliest match start for indexOf() and the latest for lastIndexOf(). A match that starts at the chosen index is allowed. When searching backward, a match can still end after that position.

Expression Result Reason
"banana".indexOf("ana", 2) 3 Next match starts at or after 2
"banana".lastIndexOf("ana", 2) 1 Last match starts at or before 2
"banana".indexOf("z") -1 No match

Once the first search succeeds, search from first + 1 to include overlaps or from first + query.length to skip them. If the first result is -1, stop because there is no first match.

const first = 'banana'.indexOf('ana'); // 1
const overlapping = 'banana'.indexOf('ana', first + 1); // 3
const nonOverlapping = 'banana'.indexOf('ana', first + 'ana'.length); // -1

Try the complete search example

Save the complete code as search-example.html in UTF-8 and open it. The default fields show 1 and 3. Enter 2 as the position to get 3 and 1. Search for ANA to get -1 twice. Empty queries and invalid positions trigger a message. Reset restores the original fields.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Compare string search positions</title>
</head>
<body>
<label for="text">Original string</label>
<input id="text" type="text" value="banana">
<label for="query">Search query</label>
<input id="query" type="text" value="ana">
<label for="position">Starting position (leave blank for the default)</label>
<input id="position" type="text" inputmode="numeric">
<button id="search" type="button">Search</button>
<button id="reset" type="button">Reset</button>
<pre id="output" aria-live="polite"></pre>
<script>
const textInput = document.querySelector('#text');
const queryInput = document.querySelector('#query');
const positionInput = document.querySelector('#position');
const output = document.querySelector('#output');

function search() {
  const text = textInput.value;
  const query = queryInput.value;
  const rawPosition = positionInput.value.trim();
  if (query === '') {
    output.textContent = 'Enter a search query.';
    return;
  }
  if (rawPosition !== '' && !/^(0|[1-9]\d*)$/.test(rawPosition)) {
    output.textContent = 'Enter a starting position of zero or higher, with no decimal places.';
    return;
  }
  const position = rawPosition === '' ? null : Number(rawPosition);
  if (position !== null && !Number.isSafeInteger(position)) {
    output.textContent = 'Enter a position within the safe integer range.';
    return;
  }
  const first = position === null
    ? text.indexOf(query)
    : text.indexOf(query, position);
  const last = position === null
    ? text.lastIndexOf(query)
    : text.lastIndexOf(query, position);
  output.textContent = `indexOf: ${first}\nlastIndexOf: ${last}`;
}

document.querySelector('#search').addEventListener('click', search);
document.querySelector('#reset').addEventListener('click', () => {
  textInput.value = 'banana';
  queryInput.value = 'ana';
  positionInput.value = '';
  search();
});
search();
</script>
</body>
</html>

Check empty queries and UTF-16 indexes

The methods accept an empty query even though the demo rejects it. The default first and last results are zero and the string length. With an explicit integer, they return the position clamped to the string’s bounds.

Indexes count UTF-16 (16-bit Unicode Transformation Format) code units. In the example, the first emoji occupies two units, so a starts at 2 although it is the second visible character. Avoid presenting that index directly as a character count.

{
  const letters = 'abc';
  console.log(letters.indexOf(''));        // 0
  console.log(letters.lastIndexOf(''));    // 3
  console.log(letters.indexOf('', 99));    // 3
  console.log(letters.lastIndexOf('', 1)); // 1

  const text = '😀a😀';
  console.log(text.indexOf('a'));         // 2
  console.log(text.lastIndexOf('😀'));    // 3
  console.log(text.length);               // 5
}