String StartsWith and EndsWith in JavaScript

The following are a simple implementation checking whether a string starts with a prefix or ends with a suffix in JavaScript.


function startsWith(str, prefix) {
    return str.lastIndexOf(prefix, 0) === 0;
}

function endsWith(str, suffix) {
    return str.indexOf(suffix, str.length - suffix.length) !== -1;
}

var start = 'http';
var end = 'com';
var str = 'http://google.com';
startsWith(str, start);
endsWith(str, end);

Here we use indexOf() method of JavaScript String object.

  • Syntax: string.indexOf(search, start)
  • Parameters: search is the string to search for; it is required. start is the position to begin the search; it is optional, with default 0.
  • Return: a number, which is the position where search occurs for the first time, or -1 if it does not occur.

The method lastIndexOf() is similar, but it starts from the end of the string. lastIndexOf(prefix, 0) starts from the first position and search backwards (but nothing left), which means it searches only once.

Another approach is to use the slice() method.


function startsWith(str, prefix) {
    return str.slice(0, prefix.length) == prefix;
}

function endsWith(str, suffix) {
    return str.slice(-suffix.length) == suffix;
}

Here we use the slice() method to extract a substring.

  • Syntax: string.slice(start, end)
  • Parameters: start is the position to begin the extraction; it is required. When start is negative, the search starts from the end of the string. end is the ending position (not included) for the extraction; it is optional, and if omitted, the extraction ends at the end of the string.
  • Return: the extracted substring.

A generic solution is to add the two methods to the String prototype.


if (typeof String.prototype.startsWith != 'function') {
    String.prototype.startsWith = function(prefix) {
        return this.slice(0, prefix.length) == prefix;
    };
}

if (typeof String.prototype.endsWith != 'function') {
    String.prototype.endsWith = function(suffix) {
        return this.slice(-suffix.length) == suffix;
    };
}

var start = 'http';
var end = 'com';
var str = 'http://google.com';
str.startsWith(start);
str.endsWith(end);

Comments

comments