[英]Javascript: find all occurrences of word in text document
我正在嘗試編寫一個 Javascript function 來查找文本文檔中所有出現的單詞的索引。 目前這就是我所擁有的——
//function that finds all occurrences of string 'needle' in string 'haystack'
function getMatches(haystack, needle) {
if(needle && haystack){
var matches=[], ind=0, l=needle.length;
var t = haystack.toLowerCase();
var n = needle.toLowerCase();
while (true) {
ind = t.indexOf(n, ind);
if (ind == -1) break;
matches.push(ind);
ind += l;
}
return matches;
}
但是,這給了我一個問題,因為即使它是字符串的一部分,它也會匹配單詞的出現。 例如,如果 needle 是“book”,haystack 是“Tom wrote a book. The book's name is Facebook for dummies”,結果是'book','book's'和'Facebook'的索引,當我只想要“書”的索引。 我怎樣才能做到這一點? 任何幫助表示贊賞。
這是我建議的正則表達式:
/\bbook\b((?!\W(?=\w))|(?=\s))/gi
解決您的問題。 嘗試使用exec()
方法。 我提供的regexp也將考慮在您提供的例句中出現的諸如“小冊子”之類的單詞:
function getMatches(needle, haystack) {
var myRe = new RegExp("\\b" + needle + "\\b((?!\\W(?=\\w))|(?=\\s))", "gi"),
myArray, myResult = [];
while ((myArray = myRe.exec(haystack)) !== null) {
myResult.push(myArray.index);
}
return myResult;
}
編輯
我已經編輯了正則表達式,以解決“小冊子”之類的詞。 我也將答案重新格式化為與您的功能相似。
你可以在這里做一些測試
嘗試這個:
function getMatches(searchStr, str) {
var ind = 0, searchStrL = searchStr.length;
var index, matches = [];
str = str.toLowerCase();
searchStr = searchStr.toLowerCase();
while ((index = str.indexOf(searchStr, ind)) > -1) {
matches.push(index);
ind = index + searchStrL;
}
return matches;
}
indexOf
返回第一本書的位置。
var str = "Tom wrote a book. The book's name is Facebook for dummies";
var n = str.indexOf("book");
我不知道發生了什么,但是我可以使用正則表達式提供更好的解決方案。
function getMatches(haystack, needle) {
var regex = new RegExp(needle.toLowerCase(), 'g'),
result = [];
haystack = haystack.toLowerCase();
while ((match = regex.exec(haystack)) != null) {
result.push(match.index);
}
return result;
}
用法:
getMatches('hello hi hello hi hi hi hello hi hello john hi hi', 'hi');
Result => [6, 15, 18, 21, 30, 44, 47]
考慮到您的book
與books
問題,您只需為"book "
提供一個空格。
或者在功能上您可以做到。
needle = ' ' + needle + ' ';
最簡單的方法可能是使用text.match(RegX)
function。例如,您可以為不區分大小寫的搜索編寫如下內容:
"This is a test. This is a Test.".match(/test/gi)
結果:
(2) ['test', 'Test']
或者這個用於區分大小寫的場景:
"This is a test. This is a Test.".match(/test/g)
結果:
['test']
let myControlValue=document.getElementById('myControl').innerText; document.getElementById('searchResult').innerText=myControlValue.match(/test/gi)
<p id='myControl'>This is a test. Just a Test </p> <span><b>Search Result:</b></span> <div id='searchResult'></div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.