How do I check if a string starts with another string in JavaScript?

To check if a string starts with another string in JavaScript, you can use the string.startsWith(searchString, index) method. The 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 parameter value is zero. The startsWith() method returns a boolean value - "true" if the given string starts with the specified string, "false" otherwise. You can also determine if the end of a given string matches the specified string or character using the endsWith() method. The methods are case-sensitive. In this JavaScript example, we check if a string starts with a given string using the startsWith() method. Click Execute to run the JavaScript String Startswith online and see the result.
How do I check if a string starts with another string in JavaScript? Execute
let str = 'JavaScript String Startswith';

console.log(str.startsWith('Java'));
Updated: Viewed: 740 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