-
Notifications
You must be signed in to change notification settings - Fork 136
Expand file tree
/
Copy pathsearch.js
More file actions
32 lines (31 loc) · 1.15 KB
/
search.js
File metadata and controls
32 lines (31 loc) · 1.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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
* v.search('morning', /rn/);
* // => 2
*
* v.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;
}