How to check if a string starts with a certain word? JavaScript essentials

/ #JavaScript


In this little guide I'll show you how you can use JavaScript to check if a string starts with a certain word.

A quick example

var str = "Hello, this is a string!";
var result = str.startsWith("Hello");
var result2 = str.startsWith("Stein");

console.log('Result: ', result);
console.log('Result2: ', result2);

If you run this example in your browser, you will see that the first variable "result" is true because the string starts with "Hello". The second variable "result2" will be false, because the string does not start with "Stein".

It's worth mentioning that "startsWith" is a case sensitive search, so "hello" would return false too!

Search position

You can also use "startsWith" to check if a word is at a certain position in a string. That would look something like this:

var str = "Hello, this is a string!";
var result = str.startsWith("this", 7);

console.log('Result: ', result);

This would return "true". The parameter we passed in here after the word we want to check for has "0" as the default value. Therefor it will search at the beginning of a string as default.

Other relevant JavaScript tutorials

How to replace a string
How to split a string

Comments

No comments yet...

Add comment

Info

Please log in to comment!

Newsletter

Subscribe to my weekly newsletter. One time per week I will send you a short summary of the tutorials I have posted in the past week.