javascript to search a string for text, in reverse:
example usage:
//similar to string.indexOf(), except that it starts searching at the end of the string.
jsUtils.reverseIndexOf = function (toSearch, toFind) {
if (toFind.length != 1) {
throw 'jsUtils.reverseIndexOf() - only implementeed for searching for 1 character';
}
var lastIndex = 0;
for (var i = 0; i < toSearch.length; i++) {
if (toSearch[toSearch.length - i - 1] === toFind) {
lastIndex = toSearch.length - i;
break;
}
}
return lastIndex - 1;
};
example usage:
jsUtils.reverseIndexOf('abcd', 'a')
0
jsUtils.reverseIndexOf('abcda', 'b')
1
jsUtils.reverseIndexOf('abcda', 'x')
-1
jsUtils.reverseIndexOf('abcda', 'a')
4
jsUtils.reverseIndexOf('abcda', '4')
-1
jsUtils.reverseIndexOf('abcda', '')
"jsUtils.reverseIndexOf() - only implementeed for searching for 1 character"
jsUtils.reverseIndexOf('abcda', 'ff')
"jsUtils.reverseIndexOf() - only implementeed for searching for 1 character"
Comments
Post a Comment