Check If JavaScript String startsWith() Another String

Article By Digamber Rawat 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');


// 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

Feel free to contact me, If you are looking for a freelance full stack Developer, with the following skills: Mongo DB, Express JS, Angualr 2+, Node JS, Loopback JS, Firebase, Ionic Framework and WordPress. I also offer remote contracting service to the clients across the globe. Hire Me