UNPKG

voca

Version:

The ultimate JavaScript string library

38 lines (32 loc) 1.2 kB
import { i as isNil } from './internal/is_nil.js'; import './is_string.js'; import { c as coerceToString } from './internal/coerce_to_string.js'; import { c as clipNumber, t as toInteger } from './internal/to_integer.js'; /** * 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 * v.search('morning', /rn/); * // => 2 * * v.search('evening', '/\d/'); * // => -1 */ function search(subject, pattern, fromIndex) { var subjectString = coerceToString(subject); var fromIndexNumber = isNil(fromIndex) ? 0 : clipNumber(toInteger(fromIndex), 0, subjectString.length); var matchIndex = subjectString.substr(fromIndexNumber).search(pattern); if (matchIndex !== -1 && !isNaN(fromIndexNumber)) { matchIndex += fromIndexNumber; } return matchIndex; } export default search;