check if string starts with substring

How to Check if String Starts With Another String in JavaScript

JavaScript supports tons of string operations to help you easily work with text. Sometimes you may need to check if a given JavaScript string starts with another string in JavaScript. In this article, we will learn how to do this.


How to Check if String Starts With Another String in JavaScript

Starting ES6 most modern browsers support a function startsWith() that is available to all strings and allows you to check if it starts with another string.

Here are a couple of examples to use this function in JS.

"Hello World!".startsWith("Hello") //returns true

You can also call it on string variables as shown below.

var sample1 = "Hello world";
var sample2 = 'Boy';
console.log(sample1.startsWith(sample2)); // returns false

If you are working with an older browser where startsWith() function is not supported, then you need to use the shim library in your web page, for this purpose.

In this article, we have learnt how to check if a JS string starts with another string.

Also read:

How to Check if Variable is Undefined in JavaScript
How to Detect Invalid Date in JavaScript
Forbidden Characters in Windows & Linux Filenames
MySQL Date Format DD/MM/YYYY in SQL Query
How to Fix MySQL Error 1153

Leave a Reply

Your email address will not be published.