Strings in JavaScript are sequences of characters enclosed within single ('') or double ("") quotes. They are essential for representing textual data and are extensively used in programming for text manipulation, output formatting, and more.
Strings can be created using single or double quotes.
let singleQuotes = 'This is a string.';
let doubleQuotes = "Another string.";
Strings can be concatenated using the + operator.
let firstName = "John";
let lastName = "Doe";
let fullName = firstName + " " + lastName; // John Doe
console.log(fullName) // John Doe
Special characters can be included in strings using escape sequences.
let text = "This is a \"quote\" inside a string.";
console.log(text) // This is a "quote" inside a string.
let text = " Hello, world! ";
let trimmedStart = text.trimStart(); // "Hello, world! "
let trimmedEnd = text.trimEnd(); // " Hello, world!"
let paddedStart = text.padStart(20, "-"); // "----- Hello, world! "
let paddedEnd = text.padEnd(20, "-"); // " Hello, world! -----"
let character = text.charAt(7); // "w"
let unicodeValue = text.charCodeAt(7); // 119
let replacedText = text.replace("world", "Universe"); // " Hello, Universe! "
let uppercaseText = text.toUpperCase(); // " HELLO, WORLD! "
console.log(text)
console.log(trimmedStart)
console.log(trimmedEnd)
console.log(paddedStart)
console.log(paddedEnd)
console.log(character)
console.log(unicodeValue)
console.log(replacedText)
console.log(uppercaseText)
Template literals allow string interpolation and multiline strings.
let name = "Alice";
let age = 30;
let greeting = `Hello, ${name}! You are ${age} years old.`;
console.log(greeting) // Hello, Alice! You are 30 years old.
Strings are fundamental data types in JavaScript used to represent text. With various methods and operations available, strings are versatile tools for text manipulation, formatting, and more.