Back to JavaScript
2026-04-217 min read

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

Learn JavaScript Program to Check Whether a String Starts and Ends With Certain Characters step by step with clear examples and exercises.

Why This Matters

Understanding how to check whether a string starts and ends with certain characters is an essential skill for any JavaScript developer. Mastering this technique allows you to write more efficient code, validate user inputs, parse data, and debug your programs effectively. By understanding the core concepts presented in this lesson, you'll be able to tackle real-world programming challenges with confidence.

Prerequisites

Before diving into the core concept, it is essential to have a good understanding of:

  1. Basic JavaScript syntax and variables
  2. Strings and string manipulation in JavaScript
  3. Control flow statements like if and else
  4. Understanding of data types and type coercion in JavaScript
  5. Familiarity with common JavaScript functions, such as length, indexOf(), slice(), and charAt()
  6. Knowledge of regular expressions (optional but recommended)

Core Concept

To check if a string starts or ends with certain characters, we can use the built-in methods startsWith(), endsWith(), and regular expressions. These methods return a boolean value indicating whether the string matches the specified condition.

Example 1: Check String Using Built-in Methods

function checkString(str, startChar, endChar) {
// Check if the string starts with 'startChar' and ends with 'endChar'
if (str.startsWith(startChar) && str.endsWith(endChar)) {
console.log(`The string "${str}" starts with "${startChar}" and ends with "${endChar}".`);
} else {
console.log(`The string "${str}" does not start or end with the specified characters.`);
}
}

// Test cases
checkString("Start", "S", "t"); // Output: The string "Start" starts with "S" and ends with "t".
checkString("End", "E", "d"); // Output: The string "End" does not start or end with the specified characters.

In this example, we define a function checkString() that takes three arguments: the input string, the character to check for at the beginning of the string, and the character to check for at the end of the string. The function uses the startsWith() and endsWith() methods to compare the input string with the specified characters and outputs a message accordingly.

Example 2: Check String Using Regular Expressions

function checkStringRegex(str, startPattern, endPattern) {
// Create regular expressions for the start and end patterns
const startRegExp = new RegExp(`^${startPattern}`);
const endRegExp = new RegExp(`${endPattern}$`);

// Check if the string matches both start and end patterns
if (startRegExp.test(str) && endRegExp.test(str)) {
console.log(`The string "${str}" starts with "${startPattern}" and ends with "${endPattern}".`);
} else {
console.log(`The string "${str}" does not start or end with the specified patterns.`);
}
}

// Test cases
checkStringRegex("Start", "S", "t"); // Output: The string "Start" starts with "S" and ends with "t".
checkStringRegex("End", "E", "d"); // Output: The string "End" does not start or end with the specified patterns.

In this example, we define a function checkStringRegex() that uses regular expressions to check if a given string starts and ends with specific patterns. Regular expressions are powerful tools for pattern matching in JavaScript and can be used as an alternative to built-in methods like startsWith() and endsWith().

Example 3: Check String Using indexOf() and charAt()

function checkString(str, startChar, endChar) {
// Check if the string starts with 'startChar' and ends with 'endChar'
const strLength = str.length;
const startIndex = str.indexOf(startChar);
const endIndex = str.lastIndexOf(endChar);

if (startIndex === 0 && endIndex === strLength - 1) {
console.log(`The string "${str}" starts with "${startChar}" and ends with "${endChar}".`);
} else {
console.log(`The string "${str}" does not start or end with the specified characters.`);
}
}

// Test cases
checkString("Start", "S", "t"); // Output: The string "Start" starts with "S" and ends with "t".
checkString("End", "E", "d"); // Output: The string "End" does not start or end with the specified characters.

In this example, we define a function checkString() that checks if a given string starts and ends with specific characters using indexOf() and charAt(). This method is useful when you don't have access to the built-in methods like startsWith() or endsWith().

Worked Example

Let's consider a scenario where we want to validate user input for file names in our application. We only accept file names that start with "file_" and end with ".txt".

function validateFileName(fileName) {
// Check if the file name starts with 'file_' and ends with '.txt'
const fileNameLength = fileName.length;
const startIndex = fileName.indexOf("file_");
const extensionIndex = fileName.lastIndexOf(".txt");

if (startIndex === 0 && extensionIndex === fileNameLength - 4) {
console.log(`The file name "${fileName}" is valid.`);
} else {
console.log(`The file name "${fileName}" is not valid.`);
}
}

// Test cases
validateFileName("file_example.txt"); // Output: The file name "file_example.txt" is valid.
validateFileName("End.txt"); // Output: The file name "End.txt" is not valid.

In this example, we define a function validateFileName() to check if a given file name is valid based on the specified criteria. If the file name starts with "file_" and ends with ".txt", it is considered valid, and an appropriate message is displayed. Otherwise, an error message is shown.

Common Mistakes

  1. Forgetting to use the startsWith() or endsWith() methods: Always remember to use these methods when checking if a string starts or ends with certain characters.
  2. Incorrect comparison: Make sure you compare the input string with the correct characters, taking into account case sensitivity and any leading/trailing spaces.
  3. Ignoring edge cases: Be aware of potential edge cases such as empty strings or strings that only contain the start or end character.
  4. Not handling errors gracefully: If your code relies on user input, make sure to handle invalid inputs appropriately and provide clear error messages for users.
  5. Using regular expressions inappropriately: While regular expressions can be powerful tools, they may not always be the most efficient solution for simple string comparisons. Use them judiciously based on the complexity of your problem.

Common Mistakes - Subheadings

Edge Cases

  1. Empty strings: Check if the input string is empty before performing any comparison.
  2. Single character strings: Handle cases where the input string only contains the start or end character.
  3. Leading/trailing spaces: Ensure that leading and trailing spaces are accounted for in your comparisons.

Regular Expressions

  1. Overuse of regular expressions: Avoid using regular expressions when simpler methods like startsWith() and endsWith() can be used instead.
  2. Inefficient regular expressions: Optimize your regular expressions to ensure they are as efficient as possible.
  3. Incorrect regular expression patterns: Make sure your regular expression patterns correctly match the desired characters or patterns.

Practice Questions

  1. Write a JavaScript function checkEmail(email) that checks if an email address starts with "user@" and ends with ".com".
  2. Modify the validateFileName() function from the worked example to also accept file names that end with either ".txt" or ".docx".
  3. Write a JavaScript program that checks if a string contains only alphabetic characters at the beginning, followed by any number of digits, and ends with an underscore (_).
  4. Write a JavaScript function checkPassword(password) that validates passwords meeting the following criteria:
  • Minimum length of 8 characters
  • Contains at least one uppercase letter
  • Contains at least one lowercase letter
  • Contains at least one digit
  • Contains at least one special character (e.g., !, @, #, $, %, etc.)
  1. Write a JavaScript function checkPhoneNumber(phoneNumber) that validates phone numbers in the following formats:
  • US format: 123-456-7890
  • International format: +1 (123) 456-7890

FAQ

Q: What happens when I use startsWith() on an empty string?

A: When you call startsWith() on an empty string, it will return false for all input strings.

Q: Can I use regular expressions to check if a string starts or ends with certain characters in JavaScript?

A: Yes, you can use regular expressions (regex) to achieve this. However, using built-in methods like startsWith() and endsWith() is generally more efficient and easier to understand for beginners.

Q: What if I want to check if a string contains certain characters anywhere in the middle instead of at the beginning or end?

A: To check for characters in the middle of a string, you can use the includes() method in JavaScript. This method returns true if the specified substring is found within the input string.

Q: What are some best practices when using regular expressions in JavaScript?

A: Some best practices include:

  • Keeping regular expressions simple and easy to understand
  • Using anchors (^ and $) to ensure that the entire string matches the pattern
  • Escaping special characters with a backslash (\)
  • Testing your regular expressions thoroughly to ensure they work as expected

Q: How can I optimize my regular expressions in JavaScript?

A: To optimize your regular expressions, consider the following tips:

  • Use character classes (e.g., [a-z]) instead of listing every possible character individually
  • Use positive lookaheads and lookbehinds to avoid unnecessary backtracking
  • Avoid capturing groups if they are not necessary
  • Use the exec() method instead of the test() method when performance is critical
JavaScript Program to Check Whether a String Starts and Ends With Certain Characters | JavaScript | XQA Learn