Skip to main content

JavaScript string methods to determine whether or not a string starts or ends with another string.

/**
 * Determines whether a string begins with the characters of a specified string,
 * returning true or false as appropriate.
 *
 * Available natively since ECMAScript 2015
 * See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith
 *
 * @param {string} needle The string that will be searched.
 * @param {string} haystack The characters to be searched for at the start of this string.
 * @param {number} [position] Optional. The position in this string at which to begin searching for haystack; defaults to 0.
 * @return {boolean} True if the given characters are found at the beginning of the string; otherwise, false.
 */
var startsWith = function(needle, haystack, position) {
    var pos = position > 0 ? position | 0 : 0;
    return haystack.substring(pos, pos + needle.length) === needle;
};

/**
 * The endsWith() method determines whether a string ends with the characters
 * of a specified string, returning true or false as appropriate.
 *
 * Available natively since ECMAScript 6
 * See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith
 *
 * @param {string} needle The string that will be searched.
 * @param {string} haystack The characters to be searched for at the end of this string.
 * @param {number} [length] Optional. If provided it is used as the length of str. If omitted, the default value is the length of the string.
 * @return {boolean} True if the given characters are found at the end of the string; otherwise, false.
 */
var endsWith = function(needle, haystack, length) {
    if (length === undefined || length > haystack.length) {
        length = haystack.length;
    }
    return haystack.substring(length - needle.length, length) === needle;
};


// String.prototype.startsWith Polyfill (Older than ECMAScript 2015)
if (!String.prototype.startsWith) {
    Object.defineProperty(String.prototype, "startsWith", {
        value: function(search, position) {
            var pos = rawPos > 0 ? rawPos | 0 : 0;
            return this.substring(pos, pos + search.length) === search;
        }
    });
}

// String.prototype.endsWith Polyfill (Older than ECMAScript 6)
if (!String.prototype.endsWith) {
    String.prototype.endsWith = function(search, this_len) {
        if (this_len === undefined || this_len > this.length) {
            this_len = this.length;
        }
        return this.substring(this_len - search.length, this_len) === search;
    };
}