IndexOf and LastIndexOf

Published by 0osh4d0wo0 in

Your task is to recreate two functions from String.object (indexOf() and lastIndexOf()).

str.indexOf(searchValue[, fromIndex])

This function will accept a string and regex as searched value, take a look at target string and return the first index if there is a match.

  • searchValue is a string or a regex object representing the value to be searched.
  • fromIndex is an optional parameter indicating the starting point (beginning from left) of your search.

If any value matches, return the first index found, else return -1.

str.lastIndexOf(searchValue[, fromIndex])

This function is the same as indexOf except it will return the last index if there is a match.

  • searchValue is a string or a regex object representing the value to be searched.
  • fromIndex is an optional parameter indicating the index of beginning of matched strings.

For example, with regex you can try to find all matches in the string but the lastIndexOf function must return the index of the character at the fromIndex parameter or lower.

If any value matches, return the last index found, else return -1.

Notes

N/A

Watch a quick demo on how Edabit works.