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.
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
nodeto start practicing coding. - Use a
for...inloop and theString.prototype.slice()method to get each substring of the givenword, starting at the beginning. - Use the
String.prototype.startsWith()method to check the current substring against thetext. - 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.