String starts with substring

Angelos Chalaris · JavaScript, String · Jul 31, 2022

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

  • Use a loop and String.prototype.slice() to get each substring of the given word, starting at the beginning.
  • Use String.prototype.startsWith() to check the current substring against the text.
  • Return the matching substring, if found. Otherwise, return undefined.
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