The startsWith() Method for JavaScript Strings [Examples]

The startsWith() String method in JavaScript will determine whether a string starts with a certain string or character. Here’s how it is used, with code examples.

startsWith() Method JavaScript Syntax

The startsWith() method can be called from any String variable.

string.startsWith(SEARCH, START)

Note that:

  • string can be any string value or variable
  • SEARCH should be the string which you want to check if string starts with
  • START is OPTIONAL
    • If specified, START will be used as the starting position when checking STRING
    • The portion of the string before START will be ignored
      • This can be useful if you want to check whether a string exists at a certain position within a string
  • A boolean value of TRUE (if the string starts with the given value) or FALSE is returned

startsWith() Examples

The below examples show how the startsWith Method is used. A string variable called test is defined, and the startsWith() method is called on it.

let test = 'Use the Force, Luke.'

test.startsWith('Use the);         // true
test.startsWith('the Force');      // false
test.startsWith('the Force', 4);   // true

Note the last example supplies a start position, so that only a portion of the string is checked.

SHARE:
Photo of author
Author
I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.

Leave a Comment