Check If JavaScript String startsWith() Another String

Last Updated on by in JavaScript

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

Hi, I'm Digamber Singh, a New Delhi-based full-stack developer, tech author, and open-source contributor with 10+ years' experience in HTML, CSS, JavaScript, PHP, and WordPress.