UNPKG

voca

Version:

The ultimate JavaScript string library

49 lines (41 loc) 1.38 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'); /** * 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 */ function endsWith(subject, end, position) { if (is_nil.isNil(end)) { return false; } var subjectString = coerce_to_string.coerceToString(subject); var endString = coerce_to_string.coerceToString(end); if (endString === '') { return true; } position = is_nil.isNil(position) ? subjectString.length : to_integer.clipNumber(to_integer.toInteger(position), 0, subjectString.length); position -= endString.length; var lastIndex = subjectString.indexOf(endString, position); return lastIndex !== -1 && lastIndex === position; } module.exports = endsWith;