我试图编写Javascript函数来查找文本文档中所有单词出现的索引。目前这是我的--
//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;
}但是,这给我带来了一个问题,因为这与单词的出现相匹配,即使它是字符串的一部分。例如,如果针头是“书”,大海捞针是“汤姆写了一本书,书的名字是”脸书“,结果是”书“、”书“和”脸书“的索引,而我只想要”书“的索引。我怎样才能做到这一点?任何帮助都是非常感谢的。
发布于 2013-09-07 21:41:34
下面是我建议的准则:
/\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;
}编辑
我已经编辑了regexp来解释像“小册子”这样的单词。我还修改了我的答案,使其类似于您的功能。
你可以做一些这里测试
发布于 2013-09-07 21:45:40
试试这个:
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");发布于 2013-09-07 21:07:21
我不知道发生了什么,但我可以提供一个更好的解决方案使用正则表达式。
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 + ' ';https://stackoverflow.com/questions/18677834
复制相似问题