[英]How can I retrieve in javascript the index of the first character of a string repeatedly in a text?
i must obtain in javascript the first index of the term "Query Response" that appears multiple times in "output_pacs" that is a variable in which is allocated the content, that is a file with multiple rows and columns.我必须在 javascript 中获取术语“查询响应”的第一个索引,该索引在“output_pacs”中多次出现,这是一个分配内容的变量,即具有多行和多列的文件。
var strutturaIndici=[];
for(var i=0;i< output.length;i++)
{
var indice_primo_carattere= output(i).indexOf("Query Response");
strutturaIndici.push(indice_primo_carattere);
}
logger.debug('StrutturaIndici:' +strutturaIndici);
The problem is that the term "Query Response" appears to me multiple times in this file, and i must obtain the first index of this term every time that it appears in this content with this code, in the console, i don't obtain the indexes, what can i do?问题是“查询响应”一词在此文件中多次出现在我面前,并且每次使用此代码出现在此内容中时,我都必须获取该词的第一个索引,在控制台中,我没有获得索引,我该怎么办? in the console i obtain this:在控制台中我得到这个:
[2021-01-30 12:53:20,002] DEBUG (js-connector:?): StrutturaIndici:
Just make a loop and call indexOf
everytime with the lastIndex
as a start to search for next term.只需创建一个循环并每次以lastIndex
调用indexOf
作为搜索下一个词的开始。 And if indexOf
returns -1, then break out of the loop.如果indexOf
返回 -1,则跳出循环。
You may look here , how the indexOf
function is defined on strings你可以看看这里, indexOf
function 是如何在字符串上定义的
var output_pacs = "test Query Response Query Response hello Query Response" var indices = []; var lastIndex = 0; while (true) { lastIndex = output_pacs.indexOf("Query Response", lastIndex + 1); if (lastIndex === -1) { // No more found break; } indices.push(lastIndex); } console.log('StrutturaIndici:' + indices);
Try Using:尝试使用:
function getIndexes(searchStr, str) { let searchStrLen = searchStr.length; if (searchStrLen == 0) { return []; } let startIndex = 0, index, indices = []; str = str.toLowerCase(); searchStr = searchStr.toLowerCase(); while ((index = str.indexOf(searchStr, startIndex)) > -1) { indices.push(index); startIndex = index + searchStrLen; } return indices; } let a = getIndexes("Query Response", "Query Response Happy New Year Query Response Happy Query Response New Year Happy Pongal Query Response New Year"); console.log(a);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.