我想检查一个字符串是否包含另一个字符串。如果包含,它应该显示在指定的网格中。
在我的列表中,我有像["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 titleText.startsWith(searchText)