JavaScript Strings

Strings in JavaScript are used to represent text. They are immutable sequences of characters, and JavaScript provides a variety of methods to work with them.

1. Creating Strings

Strings can be created using single quotes ('), double quotes ("), or backticks (`).


const singleQuoteString = 'Hello, World!';
const doubleQuoteString = "Hello, World!";
const templateString = `Hello, World!`;

            

2. String Methods

JavaScript strings come with many built-in methods for manipulation, such as length, toUpperCase, toLowerCase, indexOf, and slice.


const str = 'JavaScript is fun!';
console.log(str.length); // 18
console.log(str.toUpperCase()); // JAVASCRIPT IS FUN!
console.log(str.toLowerCase()); // javascript is fun!
console.log(str.indexOf('fun')); // 15
console.log(str.slice(0, 10)); // JavaScript

            

3. Template Literals

Template literals, enclosed in backticks (`), allow for multi-line strings and embedded expressions.


const name = 'Alice';
const age = 25;
const greeting = `Hello, my name is ${name} and I am ${age} years old.`;
console.log(greeting); // Hello, my name is Alice and I am 25 years old.

            

4. String Concatenation

Strings can be concatenated using the + operator or by using template literals.


const firstName = 'John';
const lastName = 'Doe';
const fullName = firstName + ' ' + lastName;
console.log(fullName); // John Doe

const fullNameTemplate = `${firstName} ${lastName}`;
console.log(fullNameTemplate); // John Doe

            

5. Escaping Characters

To include special characters in strings, such as quotes or newlines, you can use escape sequences.


const escapedString = 'It\'s a beautiful day!\nNew line here.';
console.log(escapedString);
// It's a beautiful day!
// New line here.