Open In App

JavaScript Program to Check Whether a String Starts and Ends With Certain Characters

Last Updated : 15 May, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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

Using startswith() and endswith() method

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.

Javascript
const findChar = 
    (input, startIndex, endIndex) => {
    const startCheck = 
        input.startsWith(startIndex);
    const endCheck = 
        input.endsWith(endIndex);

    return startCheck && endCheck;
};

const input = "GeeksforGeeks";
const startIndex = "G";
const endIndex = "s";

if (findChar(input, startIndex, endIndex)) {
    console.log("True");
} else {
    console.log("False");
}

Output
True

Using charAt() method

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.

Javascript
const input = "GeeksforGeeks";
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

Using string slicing

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

JavaScript
function startsAndEndsWith(str, start, end) {
    return str.slice(0, start.length) === start && str.slice(-end.length) === end;
}

let string = "geeksforgeeks";
let sc = "gee";
let ec = "ks";
console.log(startsAndEndsWith(string, sc, ec));

Output
true


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads