String starts with substring

Angelos Chalaris · JavaScript, String · Jul 31, 2022

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

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

Recommended snippets