JavaScript(JS) JS check whether a string starts and ends with certain characters

‮figi.www‬tidea.com

you can check whether a string starts and ends with certain characters in JavaScript/JS using the following methods:

  1. startsWith(): The startsWith() method checks whether a string starts with the specified characters and returns true if it does, and false otherwise.
const str = "Hello World!";
console.log(str.startsWith("Hello")); // Output: true
console.log(str.startsWith("World")); // Output: false
  1. endsWith(): The endsWith() method checks whether a string ends with the specified characters and returns true if it does, and false otherwise.
const str = "Hello World!";
console.log(str.endsWith("World!")); // Output: true
console.log(str.endsWith("Hello")); // Output: false

You can use both of these methods together to check whether a string starts and ends with certain characters:

const str = "Hello World!";
console.log(str.startsWith("Hello") && str.endsWith("!")); // Output: true
console.log(str.startsWith("World") && str.endsWith("!")); // Output: false

In the above example, the first console.log() statement checks whether the string starts with "Hello" and ends with "!", and returns true because both conditions are met. The second console.log() statement checks whether the string starts with "World" and ends with "!", and returns false because the first condition is not met.