UNPKG

voca

Version:

The ultimate JavaScript string library

40 lines (33 loc) 1.24 kB
'use strict'; var is_nil = require('./internal/is_nil.js'); require('./is_string.js'); var coerce_to_string = require('./internal/coerce_to_string.js'); var to_integer = require('./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 = coerce_to_string.coerceToString(subject); var fromIndexNumber = is_nil.isNil(fromIndex) ? 0 : to_integer.clipNumber(to_integer.toInteger(fromIndex), 0, subjectString.length); var matchIndex = subjectString.substr(fromIndexNumber).search(pattern); if (matchIndex !== -1 && !isNaN(fromIndexNumber)) { matchIndex += fromIndexNumber; } return matchIndex; } module.exports = search;