javascript - 如何从字符串的起始位置检查是否包含字符串
问题描述
我想检查一个字符串是否包含另一个字符串。如果包含它应该显示在指定的网格中。
在我的列表中,我有 ["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”检查?
任何帮助表示赞赏...在此先感谢。
解决方案
您只需将代码的返回语句更改为
return (titleText).indexOf(searchText) === 0;
或者,Javascript 现在方便地有一个startsWith方法 - 因此您也可以将您的 return 语句更改为此
return titleText.startsWith(searchText)
推荐阅读
- javascript - 在 Div 上使用 onclick 事件不起作用
- r - R中rbinom()的参数
- python - Python Pandas:如果没有数据则跳过然后继续写入excel
- reactjs - 反应模态组件接收相同的类
- python - 使用python从招聘广告中提取技能和职责等特征
- ios - 错误:仍在上传屏幕截图。关于 Apple App 提交
- sql - 计算相似子字符串 SQL 查询
- r - 在 R 中设置工作目录的最佳实践
- amazon-web-services - AWS Private API Gateway - 不是有效的键=值对(缺少等号)
- sql-server - SQL Server - 带有 string_agg 的索引视图