如何在冗长的字符串中查找指定单词的所有索引?
let word = 'Testing JavaScript, JavaScript is the Best, JavaScript is Ultimate';
从上述JavaScript代码字符串中找到“ JavaScript”一词的索引?其实,这是我的面试问题。
答案 0 :(得分:0)
您可以使用regular expression进行此操作。
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);
答案 1 :(得分:0)
您可以使用以下代码。
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"));