838 B
838 B
title, shortTitle, tags, expertise, cover, author, firstSeen
| title | shortTitle | tags | expertise | cover | author | firstSeen |
|---|---|---|---|---|---|---|
| String ends with substring | Ends with substring | string | beginner | blog_images/boutique-home-office-4.jpg | chalarangelo | 2022-08-01T05:00:00-04:00 |
Checks if a given string ends with a substring of another string.
- Use a
for...inloop andString.prototype.slice()to get each substring of the givenword, starting at the end. - Use
String.prototype.endsWith()to check the current substring against thetext. - Return the matching substring, if found. Otherwise, return
undefined.
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 /'