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.
[any_string].startsWith([defined_string])
// OR
[any_string].startsWith([defined_string], [position])
An example of this method is:
"hell worlds".startsWith("hello");
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.
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.
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'!😊")}})