Check If JavaScript String endsWith() Another String

By Digamber Rawat Last updated on

To check whether a string ends with a specific character or not, we are going to check out if a string in JavaScript endswith another string. ECMAScript provides us many better ways to play with the string. endsWith() method in JavaScript returns the boolean result.

JavaScript ensWith() Syntax

str.endsWith(searchString[, position])
  • searchString: The characters which needs to be searched at the end of the string.
  • position: If passed it will be used as the length of str. If ignored, the default value is the length of the string.

JavaScript endsWith() Examples

let str = 'Hello world@';

if (str.endsWith('@')) {
    console.log('The string got @');
}

// Output: The string got @

It returns boolean value to true if it matches with the specified character.

var str = 'Hello Gorgeous';
var value = str.endsWith('Gorgeous');

// Output: true

It returns boolean value to false if it doesn’t match with the specified character.

var str = 'Hello Gorgeous';
var value = str.endsWith('World');

// Output: false

The Polyfill Solution

This method may have compatibility issues, to make this method work we can use String.prototype.endsWith() MDN pollyfill.

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;
	};
}

Digamber Rawat
Digamber Rawat

Full stack developer with a passion for UI/UX design. I create beautiful and useful digital products to solve people’s problem and make their life easy.