UNPKG

awesome-string

Version:

The ultimate JavaScript string library

32 lines (31 loc) 1.18 kB
import clipNumber from 'helper/number/clip_number'; import coerceToString from 'helper/string/coerce_to_string'; import isNil from 'helper/object/is_nil'; import toInteger from 'helper/number/to_integer'; /** * Returns the first index of a `pattern` match in `subject`. * * @function search * @static * @since 1.0.0 * @memberOf Index * @param {string} [subject=''] The string where to search. * @param {string|RegExp} pattern The pattern to match. If `pattern` is not RegExp, it is transformed to `new RegExp(pattern)`. * @param {number} [fromIndex=0] The index to start searching. * @return {number} Returns the first match index or `-1` if not found. * @example * as.search('morning', /rn/); * // => 2 * * as.search('evening', '/\d/'); * // => -1 */ export default function search(subject, pattern, fromIndex) { const subjectString = coerceToString(subject); const fromIndexNumber = isNil(fromIndex) ? 0 : clipNumber(toInteger(fromIndex), 0, subjectString.length); let matchIndex = subjectString.substr(fromIndexNumber).search(pattern); if (matchIndex !== -1 && !isNaN(fromIndexNumber)) { matchIndex += fromIndexNumber; } return matchIndex; }