String extensions
In JavaScript, the startsWith()
, endsWith()
, and includes()
methods are string extension methods introduced in ES6 (ECMAScript 2015) that provide convenient ways to check the beginning, end, or presence of a substring within a string. Here's an explanation of each method with code examples:
startsWith():
The startsWith()
method checks whether a string starts with the characters of a specified string, returning true
or false
.
const str = 'Hello, world!';
console.log(str.startsWith('Hello')); // Output: true
console.log(str.startsWith('world')); // Output: false
endsWith():
The endsWith()
method checks whether a string ends with the characters of a specified string, returning true
or false
.
const str = 'Hello, world!';
console.log(str.endsWith('world!')); // Output: true
console.log(str.endsWith('Hello')); // Output: false
includes():
The includes()
method checks whether a string contains the specified substring, returning true
or false
.
const str = 'Hello, world!';
console.log(str.includes('world')); // Output: true
console.log(str.includes('universe')); // Output: false
Code Example:
const str = 'Hello, world!';
// Check if the string starts with 'Hello'
console.log(str.startsWith('Hello')); // Output: true
// Check if the string ends with 'world!'
console.log(str.endsWith('world!')); // Output: true
// Check if the string includes 'world'
console.log(str.includes('world')); // Output: true
These methods provide a convenient and efficient way to perform common string operations, such as checking for substrings or prefixes/suffixes, without needing to resort to manual string manipulation or regular expressions. They are widely supported in modern JavaScript environments and are useful for a variety of string-related tasks.
Leave a Comment