From 674bd91a723c26feb6ecba0d7869097825810081 Mon Sep 17 00:00:00 2001 From: Chalarangelo Date: Sat, 16 Jul 2022 18:00:32 +0300 Subject: [PATCH] Add substring snippets --- snippets/endsWithSubstring.md | 29 +++++++++++++++++++++++++++++ snippets/leftSubstrGenerator.md | 25 +++++++++++++++++++++++++ snippets/rightSubstrGenerator.md | 25 +++++++++++++++++++++++++ snippets/startsWithSubstring.md | 29 +++++++++++++++++++++++++++++ 4 files changed, 108 insertions(+) create mode 100644 snippets/endsWithSubstring.md create mode 100644 snippets/leftSubstrGenerator.md create mode 100644 snippets/rightSubstrGenerator.md create mode 100644 snippets/startsWithSubstring.md diff --git a/snippets/endsWithSubstring.md b/snippets/endsWithSubstring.md new file mode 100644 index 00000000000..de124cdfe8c --- /dev/null +++ b/snippets/endsWithSubstring.md @@ -0,0 +1,29 @@ +--- +title: String ends with substring +shortTitle: Ends with substring +tags: string +expertise: beginner +cover: blog_images/boutique-home-office-4.jpg +author: chalarangelo +firstSeen: 2022-08-01T05:00:00-04:00 +--- + +Checks if a given string ends with a substring of another string. + +- Use a `for...in` loop and `String.prototype.slice()` to get each substring of the given `word`, starting at the end. +- Use `String.prototype.endsWith()` to check the current substring against the `text`. +- Return the matching substring, if found. Otherwise, return `undefined`. + +```js +const endsWithSubstring = (text, word) => { + for (let i in word) { + const substr = word.slice(0, i + 1); + if (text.endsWith(substr)) return substr; + } + return undefined; +}; +``` + +```js +endsWithSubstring('Lorem ipsum dolor sit amet
'); // '
{ + for (let i in word) { + const substr = word.slice(-i - 1); + if (text.startsWith(substr)) return substr; + } + return undefined; +}; +``` + +```js +startsWithSubstring('/>Lorem ipsum dolor sit amet', '
'); // '/>' +```