String ends with substring

Angelos Chalaris · JavaScript, String · Aug 1, 2022

Checks if a given string ends with a substring of another string.

const endsWithSubstring = (text, word) => {
  for (let i in word) {
    const substr = word.slice(0, i + 1);
    if (text.endsWith(substr)) return substr;
  }
  return undefined;
};
endsWithSubstring('Lorem ipsum dolor sit amet<br /', '<br />'); // '<br /'

Recommended snippets