我正在尝试获取精确搜索字符串的索引,我构建了一个函数,该函数返回仅需要完全匹配的索引的匹配字符串
这是我的功能
getIndicesOf = (searchStr, str) => {
var searchStrLen = searchStr.length;
if (searchStrLen === 0) {
return [];
}
var startIndex = 0,
index,
indices = [];
while ((index = str.indexOf(searchStr, startIndex)) > -1) {
indices.push(index);
startIndex = index + searchStrLen;
}
console.log("detercting " , indices );
return indices;
};
console.log(getIndicesOf("go" , "go, I am going ")); // [0, 9]
我在这里查找go的索引,如何仅获取完全匹配字符串的索引?
答案 0 :(得分:2)
第一次出现的go也包含逗号。因此,这不是完全匹配。
如果您仍然想获取单词数组中 go 和 go 的所有索引,您可以使用以下脚本。
var x = "go, I am going go";
arr = x.split(" ");
arr.map((e, i) => (e === "go" || e === "go,") ? i : '').filter(String)
如果需要在字符串中查找索引,可以使用以下方法
var x = "go, I am going go";
arr = x.split(" "); var index = 0;
arr.map((e, i) => {
var occur = (e === "go" || e === "go,") ? index : '';
index+=e.length+1;
return occur}).filter(String)
答案 1 :(得分:1)
用这段代码替换while循环,
<div class="resume-item d-flex flex-column flex-md-row mb-5">
<div class="resume-content mr-auto">
<h3 class="mb-0">A.N. Other</h3>
<div class="subheading mb-3">Intelligence Analysis Masters Student</div>
<p>Interview Q&A Goes Here</p>
</div>
<div class="resume-date text-md-right">
<span class="text-primary">June 2017</span>
</div>
</div>
<div class="resume-item d-flex flex-column flex-md-row mb-5">
<div class="resume-content mr-auto">
<h3 class="mb-0">A.N. Other</h3>
<div class="subheading mb-3">Intelligence Analysis Masters Student</div>
<p>Interview Q&A Goes Here</p>
</div>
<div class="resume-date text-md-right">
<span class="text-primary">June 2017</span>
</div>
</div>
<!-- put this div where you want the count to be -->
<div id="total-count"></div>