Check Whether a String Starts and Ends With Certain Characters in JavaScript

This is a preview lesson
Register or sign in to take this lesson.
This tutorial shows how to check whether a string starts and ends with a certain characters using JavaScript. For this, we use the in-built JavaScript functions: startsWith() and endsWith().
Syntax
"example".startsWith("e")      // returns true
"test".endsWith("a")              // returns false

Example: Check If a String Starts With ‘a’ and Ends With ‘e’

// program to check if a string starts with 'a' and ends with 'e'

function CheckString(str){
    if(str.startsWith('a') && str.endsWith('e')) {
        return(`${str} starts with a and ends with e`);
    }
    else if(str.startsWith('a')) {
        return(`${str} starts with a but does not end with e`);
    }
    else if(str.endsWith('e')) {
        return(`${str} starts does not with a but end with e`);
    }
    else {
        return(`${str} does not start with e and does not end with e`);
    }
}

console.log(CheckString("apple"));
console.log(CheckString("amigo"));
console.log(CheckString("pine"));
console.log(CheckString("banana"));

Output

apple starts with a and ends with e
amigo starts with a but does not end with e
pine starts does not with a but end with e
banana does not start with e and does not end with e