How to check if string ends with specific word

Mo Ibra

Mo Ibra

Jan 6, 2023

In this article we will learn how to check if string ends with specific word in JavaScript.

It is very common to check if string ends with specific word in JavaScript in JavaScript.


Problem

Now we have a problem which is that we want to check if string ends with specific word or not.

Imagine we have a string like this:

"Hello World"

And we want to check if this string ends with "World" or not.

How to solve this problem?

This problem is easy to solve, and fortunately there is a built-in function that does it for us called endsWith().


Solution:

As we said before, we can use endsWith() method to check if string ends with another string or not.

Let's see an example

// String
const myString = "Hello World";

// Check
console.log(myString.endsWith("World"));

Output

true

We can write some lines of code based on that value.

const myString = "Hello World";

if (myString.endsWith("World")) {
    console.log('Do something');
} else {
    console.log('Do something else');
}

Output

Do something

The endsWith() method determines whether a string ends with the characters of a specified string, returning true or false as appropriate. MDN


Thank you for reading

Thank you for reading my blog. 🚀

Suggestions For More Articles: