首页 > 解决方案 > 如何从字符串的起始位置检查是否包含字符串

问题描述

我想检查一个字符串是否包含另一个字符串。如果包含它应该显示在指定的网格中。

在我的列表中,我有 ["abcd","fabcdgh","fgh","sdfgabcd","hgtabc","abcdefg"] 之类的标题,我想检查 "abcd"。这是我的代码

        <div class="picture-item__details">
        <figcaption class="picture-item__title"><?php echo $title ?></figcaption>
        </div>

  const searchText = evt.target.value.toLowerCase();
  this.shuffle.filter((element, shuffle) => {

  const titleElement = element.querySelector('.picture-item__title');
  const titleText = titleElement.textContent.toLowerCase().trim();

   return (titleText).indexOf(searchText) !== -1;

    });

在 html div 中,我动态获取标题。在顶部我有一个搜索栏,我从那里获取搜索文本。现在我想检查搜索栏是否包含“abcd”它应该只返回[“abcd”,“abcdefg”],而不是在字符串中间搜索。我使用哪个函数来找出标题是否包含从起始位置开始的“abcd”检查?

任何帮助表示赞赏...在此先感谢。

标签: javascriptjquerysearchcontainsindexof

解决方案


您只需将代码的返回语句更改为

return (titleText).indexOf(searchText) === 0;

或者,Javascript 现在方便地有一个startsWith方法 - 因此您也可以将您的 return 语句更改为此

return titleText.startsWith(searchText)

推荐阅读