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.