2013-08-21 9 views
1

如何從第二個字符獲得第二個相同的字符和索引?從第二個相同的字符jQuery索引

字符串例如:你好我正在尋找第二個相同的字符

我知道如何獲得第一「&」。

position = data.indexOf("&"); 

如何獲得第二個「&」位置?當4號碼是動態的時候?

對不起,英語不好。

+0

[在javascript中查找字符串中第n個字符的可能重複項](http://stackoverflow.com/questions/12744995/finding-the-nth-occurrence-of-a-character-in-a -string-in-javascript) –

回答

6
var data = "hello&4&I"; 
// offset is the one after the first. 
var position = data.indexOf("&", data.indexOf("&") + 1); 
console.log(position) 
// returns 7 

JSBin

哦,還有。 ..這是香草js。你不需要這個JQuery。

1

您可以

position = data.lastIndexOf("&"); 

或者使用一個通用的函數來獲得字符串中字符串的第n個位置: How to get the nth occurrence in a string?

+0

如果在句子中是字符「&」?那麼該怎麼辦? – andys

+0

查看http://stackoverflow.com/questions/14480345/how-to-get-the-nth-occurrence-in-a-string :) – Spork

相關問題