How to use charAt() method In Javascript
We define inputString and characters to check. Using charAt(), we verify the first and last characters. Then, we compare and return the vslues if conditions are met.
Example: This example shows the use of the above-explained approach.
const input = "w3wiki";
const startIndex = "G";
const endIndex = "s";
// Check if the string starts with
// the specified character
const startCheck =
input.charAt(0) === startIndex;
// Check if the string ends with
// the specified character
const endCheck =
input.charAt(input.length - 1) === endIndex;
// Log the result based on the conditions
if (startCheck && endCheck) {
console.log("True");
}
else {
console.log("False");
}
Output
True
JavaScript Program to Check Whether a String Starts and Ends With Certain Characters
In this article, We are going to learn how can we check whether a string starts and ends with certain characters. Given a string str and a set of characters, we need to find out whether the string str starts and ends with the given set of characters or not.
Examples:
Input: str = "abccba", sc = "a", ec = "a"
Output: Yes
Input: str = "geekfor geeks", cs = "g", ec = "p"
Output: No
Table of Content
- Using startswith() and endswith() method
- Using charAt() method
- Using string slicing
- Using startswith() and endswith() method