How to know if string starts with specific word

Mo Ibra

Mo Ibra

Jan 6, 2023

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

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


Problem

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

Imagine we have a string like this:

"Hello World!"

And we want to check if this string starts with "Hello" 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 startsWith().


Solution:

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

Let's see an example

// String
const myString = "Hello World!";

// Check
console.log(myString.startsWith("Hello"));

Output

true

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

const myString = "Hello World!";

if (myString.startsWith("Hello")) {
    console.log('Do something');
} else {
    console.log('Do something else');
}

Output

Do something

The startsWith() method determines whether a string begins 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: