2015-07-11 61 views
0

以下返回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); 
+0

无关,但请将'document.getElementById(“prefix”).value.toUpperCase()'放入它自己的变量中。现在阅读起来很难。看起来像一个简单的子字符串,'lastIndexOf'也可以用于换行符,不是吗? –

+0

请指定您的问题。你特别的问题是什么? –

+0

Vladimir |可以说前面给出的例子返回20和88.我需要找到这两个索引之间的最后一个换行符。 – Ethannn

回答

1

你可以去和做这样的事情: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

另一种选择将是只剁下字符串的末尾如此:

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 
0

您可以通过几种方法做到这一点。

子串

如果你想下去,你已经开始,那么你使用的路线:

str.substring(indexFirst + 1, indexLast);

工作实例

http://codepen.io/anon/pen/JdveyL

正则表达式(重新阅读您的答案后不必要)

假设|是 “得到这个之间的文本”

var re = /\|(.*?)\|/; 
var str = '|Hello|'; 
var m; 

if ((m = re.exec(str)) !== null) { 
    if (m.index === re.lastIndex) { 
     re.lastIndex++; 
    } 
    // View your result using the m-variable. 
    // eg m[0] etc. 
} 
+0

只是注意到你想要最后一个换行符。约坦的答案将是你的正确答案。 –