目前正在对字符串变量进行不同的练习。现在,当前的练习涉及字符串方法。这是我正在研究的变量。
var searchString = 'Lets search through this search string for the word, search';
我首先做的是使用这个基本的搜索方法。
var searchIndex = searchString.search('search');
结果返回值 5,表示第一个匹配的位置。我的问题是,如何找到该字符串变量中第二次搜索出现的情况?如何找到字符串变量中出现的最终搜索时间?
另外,是否可以使用 search 方法一次性找到所有 3 次搜索并返回全部 3 次?
先谢谢大家了。
肯尼思
最佳答案
您可以这样搜索:
var searchString = 'Lets search through this search string for the word, search';
function FindAllIndices(source, elem) {
var indices = [];
for(var pos = source.indexOf(elem); pos !== -1; pos = source.indexOf(elem, pos + 1)) {
indices.push(pos);
}
return indices;
}
console.log(FindAllIndices(searchString, "search"));
关于javascript - 如何使用搜索方法找到字符串变量的目标特定值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43768493/