Check If JavaScript String startsWith() Another String

By Digamber Rawat Last updated on

In this tutorial, we are going to find out how to check if a string in JavaScript startswith another string. ECMAScript offers us many powerful and easy ways to manipulate the string. JavaScript startsWith() methods checks if a string starts with a specific character.

JavaScript startsWith() Syntax

str.startsWith(searchString[, position])
  • searchString: Pass the characters which needs to be searched at the starting of the string.
  • position: This means from where the searching in your string begins at, by default it starts with 0. This parameter is optional.

JavaScript startsWith() Examples

let str = '@Hello world';

if (str.startsWith('@')) {
    console.log('The string got @');
}

// Result: The string got @

It returns boolean value to true if it matches with the specified character.

let str = 'Hello MCU fans.';
let value = str.startsWith('Hello');

// Result: true

It returns boolean value to false if it doesn’t match with the specified character.

let str = 'Hello MCU fans.';
let value = str.startsWith('MCU');

console.log(value);

// Output: false

The Polyfill Solution

To deal with compatibility issue ECMAScript offers below pollyfill. Use String.prototype.startsWith() method.

if (!String.prototype.startsWith) {
    Object.defineProperty(String.prototype, 'startsWith', {
        value: function(search, pos) {
            pos = !pos || pos < 0 ? 0 : +pos;
            return this.substring(pos, pos + search.length) === search;
        }
    });
}

Digamber Rawat
Digamber Rawat

Full stack developer with a passion for UI/UX design. I create beautiful and useful digital products to solve people’s problem and make their life easy.