javascript
  1. javascript-startswith

JavaScript startsWith()

The startsWith() method in JavaScript is a string function that checks whether a string starts with the characters of a specified string. This method returns true if the given string matches the start of the string being checked, and false otherwise.

Syntax

The syntax for startsWith() method is as follows:

string.startsWith(searchString[, position])

Here, string is the original string, searchString is the string to be searched at the beginning of the original string and position(optional) is an integer value that specifies the index to start the search.

Example

Consider the following example:

const str = 'Hello, World!';

console.log(str.startsWith('Hello')); // Output: true
console.log(str.startsWith('hello')); // Output: false
console.log(str.startsWith('World', 7)); // Output: true

In the first example, startsWith() returns true because the string 'Hello' is indeed at the beginning of str. In the second example, startsWith() returns false because 'hello' is not the same as 'Hello'. Finally, in the third example, startsWith() searches for 'World' in str starting from index 7 and returns true because 'World' is the first word at index 7.

Output

The output of the startsWith() method is either true or false, depending on whether the specified string is at the start of the original string.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>JavaScript Output</title>
</head>
<body>

<!-- Your JavaScript code goes here -->
<script>
  const str = 'Hello, World!';

  document.write('<p>' + str.startsWith('Hello') + '</p>'); // Output: true
  document.write('<p>' + str.startsWith('hello') + '</p>'); // Output: false
  document.write('<p>' + str.startsWith('World', 7) + '</p>'); // Output: true
</script>

</body>
</html>
Try Playground

Explanation

The startsWith() method checks whether a string starts with the specified characters. If the specified string is present at the start of the original string, startsWith() returns true, otherwise it returns false.

Use

startsWith() method can be used to perform various operations, such as:

  • Checking whether a URL starts with a specific protocol (http://, https://, etc.)
  • Checking if a file has a specific file extension
  • Validating input fields in web forms that must start with a specified string

Important Points

  • The startsWith() method is case-sensitive, i.e. it distinguishes between lowercase and uppercase letters.
  • The position parameter is optional and defaults to 0.

Summary

The startsWith() method in JavaScript is a powerful string function that checks whether a string starts with the specified characters. It's a simple, yet useful method that can be used for various operations such as input field validation, URL validation, and file extension checking.

Published on: