-
Notifications
You must be signed in to change notification settings - Fork 136
Expand file tree
/
Copy pathends_with.js
More file actions
40 lines (39 loc) · 1.27 KB
/
ends_with.js
File metadata and controls
40 lines (39 loc) · 1.27 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
33
34
35
36
37
38
39
40
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';
/**
* Checks whether `subject` ends with `end`.
*
* @function endsWith
* @static
* @since 1.0.0
* @memberOf Query
* @param {string} [subject=''] The string to verify.
* @param {string} end The ending string.
* @param {number} [position=subject.length] Search within `subject` as if the string were only `position` long.
* @return {boolean} Returns `true` if `subject` ends with `end` or `false` otherwise.
* @example
* v.endsWith('red alert', 'alert');
* // => true
*
* v.endsWith('metro south', 'metro');
* // => false
*
* v.endsWith('Murphy', 'ph', 5);
* // => true
*/
export default function endsWith(subject, end, position) {
if (isNil(end)) {
return false;
}
const subjectString = coerceToString(subject);
const endString = coerceToString(end);
if (endString === '') {
return true;
}
position = isNil(position) ? subjectString.length : clipNumber(toInteger(position), 0, subjectString.length);
position -= endString.length;
const lastIndex = subjectString.indexOf(endString, position);
return lastIndex !== -1 && lastIndex === position;
}