[英]Javascript - Find position of specific occurrence of a word in a string (not first or last)
如果我有一個字符串,這個字符串很多時候都使用相同的單詞,那么可以說:
“新問題,新主題,新查詢,新代碼,新語言,新答案”
在這里,我們有6次“新”這個詞,但是我想找到第4個“新”的位置。
我知道IndexOf返回第一個匹配項的位置,而LastIndexOf返回最后一個匹配項的位置,但是如何找到第四個匹配項的位置?
謝謝!
您可以使用String#indexOf
的第二個參數fromIndex
並采用先前找到的位置來開始新的搜索。
var string = "new question, new topic, new query, new code, new language, new answer", i = 0, pos = -1 do { pos = string.indexOf('new', pos + 1); i++; } while (pos !== -1 && i < 4) console.log(pos);
你可以做
let str = "new question, new topic, new query, new code, new language, new answer" let re = /new/g; let myArray, count = 4; while ((myArray = re.exec(str)) !== null && count--); console.log(count==-1 && myArray.index);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.