A string in JavaScript is a sequence of characters. It can be created using single quotes ('
), double quotes ("
), or backticks (`
).
// Using single quotes
let singleQuoted = 'Hello, World!';
// Using double quotes
let doubleQuoted = "Hello, World!";
Template literals are a feature introduced in ES6. They use backticks (`
) and allow for expression interpolation and multi - line strings.
let name = 'John';
let greeting = `Hello, ${name}!`;
The length
property returns the number of characters in a string.
let str = 'JavaScript';
console.log(str.length); // Output: 10
You can access individual characters in a string using square brackets or the charAt()
method.
let str = 'JavaScript';
console.log(str[0]); // Output: J
console.log(str.charAt(0)); // Output: J
Strings can be concatenated using the +
operator or the concat()
method.
let str1 = 'Hello';
let str2 = 'World';
// Using + operator
let result1 = str1 + ', ' + str2 + '!';
// Using concat() method
let result2 = str1.concat(', ', str2, '!');
console.log(result1); // Output: Hello, World!
console.log(result2); // Output: Hello, World!
The substring()
, substr()
, and slice()
methods can be used to extract parts of a string.
let str = 'JavaScript';
console.log(str.substring(0, 4)); // Output: Java
console.log(str.substr(0, 4)); // Output: Java
console.log(str.slice(0, 4)); // Output: Java
The indexOf()
, lastIndexOf()
, and includes()
methods can be used to search for a substring. The replace()
method can be used to replace a substring.
let str = 'JavaScript is fun';
console.log(str.indexOf('is')); // Output: 10
console.log(str.includes('fun')); // Output: true
let newStr = str.replace('fun', 'awesome');
console.log(newStr); // Output: JavaScript is awesome
The toUpperCase()
and toLowerCase()
methods can be used to convert a string to uppercase or lowercase.
let str = 'JavaScript';
console.log(str.toUpperCase()); // Output: JAVASCRIPT
console.log(str.toLowerCase()); // Output: javascript
As shown earlier, template literals can be used to create simple strings with variables.
let name = 'Jane';
let message = `Welcome, ${name}, to our website.`;
console.log(message); // Output: Welcome, Jane, to our website.
You can include expressions inside ${}
in template literals.
let num1 = 5;
let num2 = 3;
let result = `The sum of ${num1} and ${num2} is ${num1 + num2}.`;
console.log(result); // Output: The sum of 5 and 3 is 8.
Template literals allow for multi - line strings without the need for escape characters.
let multiLine = `This is a
multi - line
string.`;
console.log(multiLine);
When validating user input in forms, string manipulation methods are often used. For example, to check if an email address is in the correct format.
function validateEmail(email) {
let atIndex = email.indexOf('@');
let dotIndex = email.lastIndexOf('.');
return atIndex > 0 && dotIndex > atIndex + 1 && dotIndex < email.length - 1;
}
let email = '[email protected]';
console.log(validateEmail(email)); // Output: true
Template literals are great for displaying dynamic content on web pages.
let products = [
{ name: 'Product 1', price: 10 },
{ name: 'Product 2', price: 20 }
];
let html = '';
products.forEach(product => {
html += `<div>
<h2>${product.name}</h2>
<p>Price: $${product.price}</p>
</div>`;
});
document.body.innerHTML = html;
+
operator is usually faster. However, for multiple concatenations, using an array and then joining it can be more performant.let arr = [];
for (let i = 0; i < 10; i++) {
arr.push(i.toString());
}
let result = arr.join('');
JavaScript string manipulation methods and template literals are powerful tools that every JavaScript developer should master. String manipulation methods provide a wide range of functionality for working with strings, such as accessing characters, concatenating, and searching. Template literals offer a more convenient way to work with dynamic and multi - line strings. By following common practices and best practices, you can write more readable, maintainable, and performant code.