JavaScript(JS) JS check whether a string starts and ends with certain characters
figi.wwwtidea.com
you can check whether a string starts and ends with certain characters in JavaScript/JS using the following methods:
startsWith()
: ThestartsWith()
method checks whether a string starts with the specified characters and returnstrue
if it does, andfalse
otherwise.
const str = "Hello World!"; console.log(str.startsWith("Hello")); // Output: true console.log(str.startsWith("World")); // Output: false
endsWith()
: TheendsWith()
method checks whether a string ends with the specified characters and returnstrue
if it does, andfalse
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.