Created
June 18, 2016 14:55
-
-
Save black-black-cat/798b8d165de67b43bdb0b2c3222bfd4a to your computer and use it in GitHub Desktop.
匹配关键词在字符串中各处出现的位置的索引,组成数组
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @param {String} substr 用来搜索的子串 | |
* @param {String} str 被搜索的字符串 | |
* @return {Array} 由匹配到的索引组成的数组 | |
*/ | |
function getIndexes(substr, str) { | |
var arr = []; | |
var index; | |
var len = 0; | |
var slicedStr = str; | |
var getIdx = function() { | |
var i; | |
if ((i = slicedStr.search(substr)) == -1) { | |
return; | |
} | |
len = str.length - slicedStr.length; | |
arr.push( (index = i + len) ); | |
slicedStr = str.slice(index + substr.length); | |
getIdx(); | |
} | |
getIdx(); | |
return arr; | |
} | |
var a = getIndexes('abc', 'abcdabcdabc'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment