awesome-string
Version:
The ultimate JavaScript string library
40 lines (39 loc) • 1.3 kB
JavaScript
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
* as.endsWith('red alert', 'alert');
* // => true
*
* as.endsWith('metro south', 'metro');
* // => false
*
* as.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;
}