Monday, September 17, 2018

OrdinalIndexOf for JavaScript

A quick port of the Apache Commons StringUtils.OrdinalIndexOf function for JavaScript:

var ordinalIndexOf = function (str, searchStr, ordinal, lastIndex) {
if (str == null || searchStr == null || ordinal <= 0) {
return -1;
}
if (searchStr.length == 0) {
return lastIndex ? str.length : 0;
}
let found = 0;
// set the initial index beyond the end of the string
// this is to allow for the initial index decrement/increment
let index = lastIndex ? str.length : -1;
do {
if (lastIndex) {
index = str.lastIndexOf(searchStr, index - 1); // step backwards thru string
} else {
index = str.indexOf(searchStr, index + 1); // step forwards through string
}
if (index < 0) {
return index;
}
found++;
} while (found < ordinal);
return index;
}


No comments:

Post a Comment

Note: Only a member of this blog may post a comment.