字符串是否以子串开头

JavaScriptJavaScriptBeginner
立即练习

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

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

简介

在本实验中,我们将探索如何使用 JavaScript 检查给定字符串是否以另一个字符串的子串开头。我们将学习如何使用 for...in 循环和 String.prototype.slice() 获取给定单词的每个子串,以及使用 String.prototype.startsWith() 检查当前子串是否与文本匹配。完成本实验后,你将能够在 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{{"`字符串是否以子串开头`"}} javascript/data_types -.-> lab-28625{{"`字符串是否以子串开头`"}} javascript/arith_ops -.-> lab-28625{{"`字符串是否以子串开头`"}} javascript/comp_ops -.-> lab-28625{{"`字符串是否以子串开头`"}} javascript/cond_stmts -.-> lab-28625{{"`字符串是否以子串开头`"}} javascript/loops -.-> lab-28625{{"`字符串是否以子串开头`"}} end

检查字符串是否以子串开头的函数

要检查给定字符串是否以另一个字符串的子串开头,请执行以下步骤:

  • 打开终端/SSH 并输入 node 开始练习编码。
  • 使用 for...in 循环和 String.prototype.slice() 方法从开头获取给定 word 的每个子串。
  • 使用 String.prototype.startsWith() 方法将当前子串与 text 进行比较。
  • 如果找到匹配的子串,则返回它。否则,返回 undefined

以下是一个实现此功能的 JavaScript 函数:

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

你可以按如下方式调用此函数:

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

总结

恭喜你!你已经完成了“字符串是否以子串开头”实验。你可以在 LabEx 中练习更多实验来提升你的技能。

您可能感兴趣的其他 JavaScript 教程