In JavaScript, checking whether a string starts or ends with specific characters is a fundamental task that you might often need to perform in various applications. This capability is especially useful in form validations, parsing input data, and implementing search functionalities where precise string matching is required.
In this article, you will learn how to check if a string starts and ends with certain characters using straightforward examples. Explore how to employ built-in string methods to make these determinations efficiently.
startsWith()
MethodUnderstand that the startsWith()
method determines if a string begins with the characters of a specified string.
Prepare a string variable and apply the startsWith()
method.
let str = "Hello world!";
let startsWithHello = str.startsWith("Hello");
console.log(startsWithHello); // Outputs: true
The startsWith()
method checks the variable str
to see if it begins with "Hello". Since it does, the output is true
.
Remember that startsWith()
is case-sensitive.
Test the function with a different case to see the effect.
let str = "hello world!";
let startsWithHello = str.startsWith("Hello");
console.log(startsWithHello); // Outputs: false
In this example, even though str
starts with "hello", because startsWith()
is case-sensitive and "Hello" is not exactly the same as "hello", the result is false
.
endsWith()
MethodKnow that the endsWith()
method is used to check if a string ends with the characters of a specified string, similar to startsWith()
but for the end of the strings.
Create a string variable and apply the endsWith()
method.
let str = "Hello world!";
let endsWithWorld = str.endsWith("world!");
console.log(endsWithWorld); // Outputs: true
Here, str
is checked to see if it ends with "world!". Since it does, the output is true
.
endsWith()
Note the case sensitivity in endsWith()
similar to startsWith()
.
Test a case variation to confirm.
let str = "Hello World!";
let endsWithWorld = str.endsWith("world!");
console.log(endsWithWorld); // Outputs: false
As endsWith()
is also case-sensitive, "World!" and "world!" do not match due to the uppercase "W", thus the result is false
.
The startsWith()
and endsWith()
methods in JavaScript offer a robust and straightforward approach to check if strings start or end with certain characters. These methods are invaluable for various programming scenarios, particularly those involving string manipulation and validation. By mastering these techniques, you enhance your ability to handle strings effectively, ensuring your applications can perform precise string matching and validations where necessary.