2014-09-11 52 views
0

我做了如下的代碼,但我並不真的很高興它的方式完成。 也許是一個最簡單的方法找出例如所有選定字符的索引是一個字符串? 我知道我可以使用indexOf()(我知道我可以在索引後搜索)或match(),但它總是返回第一個出現元素的索引。我確實嘗試split()字符串到數組並使用​​但仍然不是這樣。最簡單的方法找到最後發生的選定字符索引

它找到最後出現的字符的索引什麼是我的目標。

function returnLastUnderscorePosition(string, offset) {    
     if (!string || string.match('_') === null) { 
      return 0; 
     } 

     var intPosition = string.match('_').index + 1, 
       strStringToFind = string.slice(intPosition); 

     if (strStringToFind.match('_')) { 
      intPosition += returnLastUnderscorePosition(strStringToFind, intPosition); 
     } else { 
      return (offset) ? intPosition + offset : intPosition; 
     } 

    } 

感謝

+0

'如果(strStringToFind.match( '_'))'是真的,比你什麼都沒有返回('undefined')... – Regent 2014-09-11 08:26:37

+1

['String.prototype.l astIndexOf()'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/lastIndexOf)? – Yoshi 2014-09-11 08:28:02

回答

2

您可以使用lastIndexOf()得到一個字符串的最後出現處的另一個位置:

function returnLastUnderscorePosition(string, offset) {    
    if (!string || string.match('_') === null) 
     return 0; 

    var intPosition = string.lastIndexOf('_'); 
    return (offset) ? intPosition + offset : intPosition; 
} 

Example fiddle

Further reading on lastIndexOf()