JavaScript provides several operators and methods to work with strings. Strings are sequences of characters used to represent text. In JavaScript, strings are immutable, meaning that once they are created, they cannot be altered directly. However, you can create new strings based on existing ones.
Basic String Operators
Concatenation Operator (+)
The concatenation operator + is used to combine two or more strings into a single string.
let name = "Alice";
let message = greeting + name; // "Hello, Alice"
console.log(message);
Concatenation Assignment Operator (+=)
The concatenation assignment operator += appends a string to an existing string variable.
message += "Bob"; // "Hello, Bob"
console.log(message);
String Methods
JavaScript provides various methods for string manipulation. Some of the most commonly used methods include length, charAt(), substring(), slice(), indexOf(), replace(), and template literals.
Length Property
The length property returns the number of characters in a string.
console.log(text.length); // 13
charAt()
The charAt() method returns the character at a specified index in a string.
console.log(text.charAt(0)); // "J"
console.log(text.charAt(4)); // "S"
substring()
The substring() method extracts a part of a string and returns it as a new string without modifying the original string.
let part = text.substring(0, 5); // "Hello"
console.log(part);
slice()
The slice() method extracts a section of a string and returns it as a new string. It can take negative indices, which count from the end of the string.
console.log(text.slice(0, 4)); // "Java"
console.log(text.slice(-6)); // "Script"
indexOf()
The indexOf() method returns the index of the first occurrence of a specified value in a string. If the value is not found, it returns -1.
console.log(text.indexOf("World")); // 7
console.log(text.indexOf("world")); // -1 (case-sensitive)
replace()
The replace() method searches for a specified value in a string and replaces it with another value.
let newText = text.replace("World", "JavaScript"); // "Hello, JavaScript!"
console.log(newText);
Template Literals
Template literals, introduced in ES6, allow for easier string interpolation and multi-line strings. Template literals are enclosed by backticks (`) instead of single or double quotes.
String Interpolation
String interpolation allows you to embed expressions within a string using ${expression} syntax.
let age = 25;
let message = `My name is ${name} and I am ${age} years old.`;
console.log(message); // "My name is Alice and I am 25 years old."
Multi-line Strings
Template literals make it easy to create multi-line strings.
multi-line
string.`;
console.log(multiLine);
Practice Excercise Practice now