JavaScript String endsWith()


In JavaScript, the endsWith() method determines whether the given string ends with a specific sequence of characters. Let’s take a look at syntax and examples of the Javascript string endsWith() method.

Note: If you want to determine whether the given string begins with a specific sequence of characters then you can use JavaScript String startsWith()

endsWith() Syntax

The syntax of the endsWith() method is:

endsWith(searchString, length)

endsWith() Parameters

The endsWith() method takes two parameters.

  • searchString (required): The characters that need to be searched at the start of the string.
  • length(optional): Its an optional parameter which takes the length of the string to search in a given string. If not specified by default it takes str.length

endsWith() Return Value

The endsWith() function returns true if the given characters are found at the end of the string. Otherwise, it returns false.

Note: The endsWith() method is case-sensitive.

JavaScript String endsWith() examples

In this example, you can notice that the endsWith() method is case-sensitive as the exact match returns true else returns false, as shown in the below code.

const text = 'Hello, Welcome to JavaScript World';
console.log(text.endsWith('World')); // true
console.log(text.endsWith('world')); // false



Since we have not given any position parameter, it will start from position 0 of the string.

JavaScript endsWith() example with length parameter

If we do not specify the length parameter, the “searchString” will try to match at the end of the string, and if the string doesn’t match the given “searchString,” the method returns false, as shown below.

In the below example we are searching for a string “Welcome” without passing the length parameter. The endsWith() method will match if the “Welcome” is present at the end of the string as it takes the total string length here. Since it doesn’t end with a given “searchStringthe method will return false as shown in the below code.

const text = 'Hello, Welcome to JavaScript World';
console.log(text.endsWith('Welcome')); // false



Now, when we pass the exact length as a parameter it determines the string length and it will match the given “searchString” ends within the length of the string. The example code is shown below.

const text = 'Hello, Welcome to JavaScript World';
console.log(text.endsWith('Welcome',14)); //true


Leave a Reply

Your email address will not be published. Required fields are marked *

Sign Up for Our Newsletters

Get notified on the latest articles

You May Also Like
JavaScript Array slice()

JavaScript Array slice()

Table of Contents Hide slice() Exampleslice() Syntaxslice() Parametersslice() Return ValueExample 1: Clone an array using the JavaScript slice() methodExample 2: JavaScript slice() methodExample 3: JavaScript slice() With Negative indexExample 4:…
View Post