Skip to content

Instantly share code, notes, and snippets.

@petergi
Last active December 27, 2023 22:37
Show Gist options
  • Select an option

  • Save petergi/4e4073d279b9cf72e15b1a58bcb49dea to your computer and use it in GitHub Desktop.

Select an option

Save petergi/4e4073d279b9cf72e15b1a58bcb49dea to your computer and use it in GitHub Desktop.
Checks if a given string starts with a substring of another string
// Changed the loop to start from the end of the word string and iterate backwards.
// This allows us to avoid unnecessary slicing operations.
//Used substring instead of slice since we only need to get the substring starting from i to the end.
/**
* Finds the longest substring of the word that is a prefix of the text.
*
* @param {string} text - The text to search for the substring.
* @param {string} word - The word to find the substring from.
* @return {string|undefined} The longest substring that is a prefix of the text, or undefined if no such substring exists.
*/
function startsWithSubstring(text, word) {
for (let i = word.length - 1; i >= 0; i--) {
const substr = word.substring(i)
if (text.startsWith(substr)) return substr
}
return undefined
}
startsWithSubstring("/>Lorem ipsum dolor sit amet", "<br />") //= `/>`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment