OneBite.Dev - Coding blog in a bite size

find the position of the last occurrence of a substring in a string in Javascript

Code snippet on how to find the position of the last occurrence of a substring in a string in Javascript

function findLastOccurrenceOfSubstring(string, substring) {
  return string.lastIndexOf(substring);
}

This code provides a function that takes two parameters - a string and a substring - and returns the last position of the occurrence of the substring within the string.

It does this using the built-in Javascript string method, lastIndexOf(). This method takes a substring as a parameter and returns the position of the last occurrence of the substring within the string, or -1 if the substring doesn’t exist.

In the example above, the code creates a function called findLastOccurrenceOfSubstring(). This function takes two parameters: a string and a substring. It then calls the lastIndexOf() method on the string and passes the substring as a parameter.

The function will then return the position of the last occurrence of the substring in the string, or -1 if the substring doesn’t exist.

javascript