Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

communitycreator
javascript
string

How to use the startsWith() method in JavaScript

Theodore Kelechukwu Onyejiaku

The startsWith() method in JavaScript is a String method that is used to check if a particular string starts with the exact string that is passed as an argument.


The startsWith() method is case sensitive.


Syntax


[any_string].startsWith([defined_string])

// OR
[any_string].startsWith([defined_string], [position])

An example of this method is:


"hell worlds".startsWith("hello");

Parameters

  • defined_string: This is the specified string you want to search for in the main string.

  • position: This is the position you want the search to start from. It is a zero-based index numbering.

Return value

The startsWith() method returns a Boolean value which could either be true or false.

If the string actually begins with the specified argument, then the true value is returned. Otherwise, false is returned.

Explanation

In the code above, as the user inputs text into the textbox, if it starts with “edpresso,” then we alert the user that their input starts with “edpresso.”

This is achieved with the JavaScript line of code below:

let inputBox = document.getElementById("inputBox");
inputBox.addEventListener("input", (event) => {
  if (event.target.value.toLowerCase().startsWith("edpresso")) {
    alert("yipppeee!\nInput starts with 'edpresso'!😊")
  }
})

RELATED TAGS

communitycreator
javascript
string

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku
RELATED COURSES

View all Courses

Keep Exploring