Introduction to Strings String Declaration - Template Literals String Methods - Common String Methods - ES6+ String Methods String Properties String Concatenation String Comparison
Strings are a fundamental data type in JavaScript used to represent textual data. With the introduction of ES6, JavaScript added several new features and methods to make string manipulation more powerful and flexible.
Template literals, introduced in ES6, allow embedding expressions inside strings using backticks (`). They support multi-line strings and embedded expressions.
const name = 'John';
const greeting = `Hello, ${name}!
Welcome to our website.`;
console.log(greeting);Output:
Hello, John! Welcome to our website.
| Method | Description | Example |
|---|---|---|
str.includes(substring) |
Determines whether a string contains the specified substring | const includes = 'hello'.includes('ell'); // true |
str.startsWith(substring) |
Determines whether a string starts with the specified substring | const startsWith = 'hello'.startsWith('he'); // true |
str.endsWith(substring) |
Determines whether a string ends with the specified substring | const endsWith = 'hello'.endsWith('lo'); // true |
str.repeat(count) |
Returns a new string with a specified number of copies of the original string | const repeated = 'ha'.repeat(3); // 'hahaha' |
Strings can be concatenated using the + operator or the concat() method.
const str1 = 'Hello';
const str2 = 'World';
const combined = str1 + ' ' + str2; // 'Hello World'
const combined2 = str1.concat(' ', str2); // 'Hello World'Strings can be compared using comparison operators (<, >, <=, >=, ==, ===).
const str1 = 'apple';
const str2 = 'banana';
console.log(str1 < str2); // true
console.log(str1 === 'apple'); // trueTip
Use template literals for multi-line strings and embedded expressions. Leverage ES6+ string methods like includes, startsWith, and endsWith for more expressive string operations. Always consider the performance implications of string operations, especially when dealing with large strings.
[EOF]
