One of the everyday tasks that developers need to perform when working with strings in JavaScript is to check if a string starts and ends with specific characters. In this article, we will show you how to create a JavaScript program that checks if a string begins and ends with certain characters.

Introduction to String Manipulation in JavaScript

String manipulation is an essential aspect of programming, and JavaScript provides various built-in methods to perform string manipulation. For instance, the substring method allows you to extract a part of a string, while the concat process allows you to join two or more strings.

One of the most fundamental operations that can be performed on strings is to check if a string starts or ends with specific characters. This is useful in many scenarios, such as when you want to validate user inputs or when you want to extract information from a string.

Implementing the Program

To implement the program to check if a string starts and ends with specific characters, we will use the startsWith and endsWith methods. These methods are part of the ECMAScript 6 specification and are supported by most modern browsers.

Here is the code for the program:

				
					function checkString(str, startsWith, endsWith) {
  if (str.startsWith(startsWith) && str.endsWith(endsWith)) {
    return true;
  } else {
    return false;
  }
}

				
			

In the above code, we have defined a function called checkString that takes three parameters: str, startsWith, and endsWith. The function checks if the str parameter starts with the startsWith parameter and ends with the endsWith parameter. If both conditions are proper, the function returns true. Otherwise it returns false.

Using the Program

Using the program is straightforward. Call the checkString function and pass the string you want to check, along with the characters you want to use for the starting and ending characters.

Here is an example:

				
					let string = "Hello World";
let startsWith = "H";
let endsWith = "d";

let result = checkString(string, startsWith, endsWith);

console.log(result); // Output: true

				
			

In the above example, we have defined a string with the value "Hello World". In addition, we have also defined two variables startsWith and endsWith, with the values "H" and "d", respectively.

Finally, we have called the checkString function and passed the three variables as arguments. The function returns true, indicating that the string “Hello World” starts with “H” and ends with “d”.

We have shown you how to create a JavaScript program to check if a string starts and ends with specific characters. Using the startsWith and endsWith methods, you can efficiently perform this task and validate user inputs or extract information from strings.


Thanks for reading. Happy coding!