check the first character of a string matches a given character in javascript

One way to check if the first character of a string matches a given character is to use the substr() method to get the first character of the string, and then compare it to the given character using the JavaScript comparison operator ===. Here's an example code block:

index.tsx
let myString = "example string";
let firstChar = myString.substr(0, 1);
let givenChar = "e";

if (firstChar === givenChar) {
  console.log("The first character of myString matches the given character!");
} else {
  console.log("The first character of myString does not match the given character.");
}
301 chars
10 lines

In this example, the substr() method is used to get the first character of the myString variable and store it in the firstChar variable. Then, the === operator is used to compare firstChar to the givenChar variable to see if they are the same. Depending on the result of this comparison, the appropriate message is logged to the console.

gistlibby LogSnag