Using JavaScript String startsWith() Method

To check if a string starts with another string in JavaScript, you can use the string.startsWith(searchString, index) method. The string.startsWith() method determines if the start of this string matches the specified string or character. The first parameter specifies the search string. The second parameter is optional and specifies the index in the given string from which to search. The default value is zero. The string.startsWith() method returns a boolean value - "true" if the given string starts with the specified string, "false" otherwise. You can also determine if a string ends with a specified string by calling the string.endsWith() method. The methods are case-sensitive. In this JavaScript String startsWith example, we check if a string starts with a given string using the startWith() method with the default "index" parameter. Click Execute to run the JavaScript String startsWith Example online and see the result.
Using JavaScript String startsWith() Method Execute
let str = 'JavaScript String Startswith';

console.log(str.startsWith('JavaScript'));
Updated: Viewed: 2536 times

JavaScript string startsWith() method

The string.startsWith(searchString, index) method is used to check if the given string starts with the specified string's characters. The startsWith() method is case-sensitive.

JavaScript startsWith() Syntax
string.startsWith(searchString, index)

Where:
  • searchString: the string or character to search for. If the search string is a RegExp, a TypeError is raised
  • index (optional): the index from which to search (default value is 0)
JavaScript Check if String Starts with Specified String Example
let str = 'JavaScript String Startswith';

console.log(str.startsWith('String'));

// output: false

How to check if a string ends with a specified string?

To check if the end of a string is the same as a specified string, use the string.endsWith(searchString, length) method. The endsWith() method is case-sensitive.

JavaScript endsWith() Syntax
string.endsWith(searchString, length)

Where:
  • searchString: the string or character to search for. If the search string is a RegExp, a TypeError is raised.
  • length (optional): The length of the string to search for (the default value is the length of the given string). If the value is greater than the search string's length, then the search is carried out over the entire string; if it is less than the given string, it will be cut to the specified length. The method will return "false" if a negative value is specified.
JavaScript Check if String Ends with Specified String Example
let str = 'JavaScript String startsWith Example';

console.log(str.endsWith('Example'));

// output: true

See also