String Ends with Substring

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will explore how to check if a given string ends with a substring of another string using JavaScript. We will use a for...in loop and String.prototype.slice() to get each substring of the given word, starting at the end. Then, we will use String.prototype.endsWith() to check the current substring against the text. By the end of this lab, you will have a solid understanding of how to use these string methods to find matching substrings in JavaScript.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/BasicConceptsGroup -.-> javascript/cond_stmts("`Conditional Statements`") javascript/BasicConceptsGroup -.-> javascript/loops("`Loops`") subgraph Lab Skills javascript/variables -.-> lab-28286{{"`String Ends with Substring`"}} javascript/data_types -.-> lab-28286{{"`String Ends with Substring`"}} javascript/arith_ops -.-> lab-28286{{"`String Ends with Substring`"}} javascript/comp_ops -.-> lab-28286{{"`String Ends with Substring`"}} javascript/cond_stmts -.-> lab-28286{{"`String Ends with Substring`"}} javascript/loops -.-> lab-28286{{"`String Ends with Substring`"}} end

A Function to Check if a String Ends with a Substring

To check if a given string ends with a substring of another string, follow these steps:

  1. Open the Terminal/SSH and type node to start practicing coding.
  2. Use a for...in loop and String.prototype.slice() to get each substring of the given word, starting at the end.
  3. Use String.prototype.endsWith() to check the current substring against the text.
  4. Return the matching substring, if found. Otherwise, return undefined.

Here's the code snippet to implement the above steps:

const endsWithSubstring = (text, word) => {
  for (let i in word) {
    const substr = word.slice(0, i + 1);
    if (text.endsWith(substr)) return substr;
  }
  return undefined;
};

You can test the function with the following example:

endsWithSubstring("Lorem ipsum dolor sit amet<br /", "<br />"); // '<br /'

Summary

Congratulations! You have completed the String Ends With Substring lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like