How to use string slicing In Javascript
In this approach we are using the slice method to extract substrings from the input string. It checks if the extracted substring from the start of the string matches the specified start string and if the extracted substring from the end of the string matches the specified end string. If both conditions are true we returns true otherwise returns false.
Example: This example uses string slicing to check whether a string starts and ends with certain characters
function startsAndEndsWith(str, start, end) {
return str.slice(0, start.length) === start && str.slice(-end.length) === end;
}
let string = "w3wiki";
let sc = "gee";
let ec = "ks";
console.log(startsAndEndsWith(string, sc, ec));
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