如何在冗长的字符串中查找指定单词的所有索引?
let word = 'Testing JavaScript, JavaScript is the Best, JavaScript is Ultimate';
在 JavaScript 代码中从上面的字符串中找到单词“JavaScript”的索引?实际上,这是我的面试问题。
如何在冗长的字符串中查找指定单词的所有索引?
let word = 'Testing JavaScript, JavaScript is the Best, JavaScript is Ultimate';
在 JavaScript 代码中从上面的字符串中找到单词“JavaScript”的索引?实际上,这是我的面试问题。
您可以使用以下代码。
let str = 'Testing JavaScript, JavaScript is the Best, JavaScript is Ultimate';
function findAllIndexes(string,word){
let result = [];
let dif = 0;
while(true){
let index = string.indexOf(word);
if(index === -1) break;
else{
result.push(index + dif);
let cur = string.length;
string = string.substring(index + word.length);
dif += cur - string.length;
}
}
return result;
}
console.log(findAllIndexes(str,"JavaScript"));
您可以使用正则表达式来做到这一点。
let word = 'Testing JavaScript, JavaScript is the Best, JavaScript is Ultimate';
var regex = /JavaScript/gi,result,indices=[];
while((result=regex.exec(word)))
{
indices.push(result.index);
}
console.log(indices);