javascript - 在索引之间搜索

标签 javascript

以下返回 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

.substring() docs

.lastIndexOf() docs

另一种选择是仅 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/

相关文章:

JavaScript 定时器暂停

javascript - 如何获取 <ol> 中的列表编号以匹配

javascript - CKEditor5 CodeBlock 的使用示例

javascript - 执行绑定(bind)时的 WinJS 通知

javascript - rails link_to 发送 get 而不是 post

javascript在函数构造函数中访问 "this"

javascript - 如何检测一个点是否在圆内?

javascript - 如何在ASP.NET中的Linkbutton中管理右键单击 "Open in new tab"和 "Open in new windows"?

javascript - 让 django 代码在页面加载后运行

javascript - 获取构成 Jquery 或 Javascript 中的元素的 HTML?