How to use startswith() and endswith() method In Javascript
The startswith() method checks for the characters at the beginning of the string and the endswith() method checks for characters at the end of the given string. If both return true then it will assure the presence of that character at the end and beginning of the string.
Example: This example shows the use of the above-explained appraoch.
const findChar =
(input, startIndex, endIndex) => {
const startCheck =
input.startsWith(startIndex);
const endCheck =
input.endsWith(endIndex);
return startCheck && endCheck;
};
const input = "w3wiki";
const startIndex = "G";
const endIndex = "s";
if (findChar(input, startIndex, endIndex)) {
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