String Starts 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 starts with a substring of another string using JavaScript. We will learn how to use for...in loop and String.prototype.slice() to get each substring of a given word, and String.prototype.startsWith() to check if the current substring matches the text. By the end of this lab, you will be able to efficiently find if a string starts with a specific substring 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-28625{{"`String Starts with Substring`"}} javascript/data_types -.-> lab-28625{{"`String Starts with Substring`"}} javascript/arith_ops -.-> lab-28625{{"`String Starts with Substring`"}} javascript/comp_ops -.-> lab-28625{{"`String Starts with Substring`"}} javascript/cond_stmts -.-> lab-28625{{"`String Starts with Substring`"}} javascript/loops -.-> lab-28625{{"`String Starts with Substring`"}} end

Function to Check If String Starts With Substring

To check if a given string starts with a substring of another string, follow the steps below:

  • Open the Terminal/SSH and type node to start practicing coding.
  • Use a for...in loop and the String.prototype.slice() method to get each substring of the given word, starting at the beginning.
  • Use the String.prototype.startsWith() method to check the current substring against the text.
  • If a matching substring is found, return it. Otherwise, return undefined.

Here's a JavaScript function that does this:

const startsWithSubstring = (text, word) => {
  for (let i in word) {
    const substr = word.slice(-i - 1);
    if (text.startsWith(substr)) return substr;
  }
  return undefined;
};

You can call this function as follows:

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

Summary

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

Other JavaScript Tutorials you may like