以下返回 2 个索引。
我想在这两个索引之间查找最后一个换行符。
var str = document.getElementById("output").value;
var indexFirst = str.indexOf(document.getElementById("prefix").value.toUpperCase());
var indexLast = str.lastIndexOf(document.getElementById("prefix").value.toUpperCase());
alert(indexFirst + " | " + indexLast);
最佳答案
你可以去做这样的事情:Working jsFiddle
var newStr = str.substring(indexFirst, indexLast); // get only the relevant part of the string
var pos = newStr.lastIndexOf("\n"); // find the last new line's index
alert(indexFirst + pos); // add the found index to the initial search index
另一种选择是仅 chop 字符串的末尾,如下所示:
var newStr = str.substring(0, indexLast); // chop off the end
var pos = newStr.lastIndexOf("\n", indexStart); // search the last index starting from indexStart
alert(pos); // no need to add indexStart this way
关于javascript - 在索引之间搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31359138/