A string is a sequence of characters used to represent text. In JavaScript, strings are written inside single quotes ('')
, double quotes ("")
, or backticks (``)
for template literals.
const name = "Alice";
const greeting = 'Hello';
const message = `Welcome, ${name}!`; // Template literal
length
– Returns the number of characterstoUpperCase()
– Converts to uppercasetoLowerCase()
– Converts to lowercasecharAt(index)
– Returns the character at a specific indexincludes(substring)
– Checks if a substring existsindexOf(substring)
– Returns the position of a substringreplace(old, new)
– Replaces part of the stringslice(start, end)
– Extracts part of a stringtrim()
– Removes whitespace from both endsconst text = " JavaScript is fun! ";
console.log(text.length); // 22
console.log(text.trim()); // "JavaScript is fun!"
console.log(text.toUpperCase()); // " JAVASCRIPT IS FUN! "
console.log(text.includes("fun")); // true
Use backticks `
and ${}
to embed variables:
const name = "Bob";
const message = `Hello, ${name}!`;
console.log(message); // Output: Hello, Bob!
Strings are one of the most used data types in JavaScript. Use string methods to clean, format, and manipulate text easily.
Creating strings using single, double quotes, or backticks.
let str1 = 'Hello, world!'; let str2 = "Hello, world!"; let name = `John`; console.log(str1, str2, name); // Output: Hello, world! Hello, world! John
Using string methods like charAt(), indexOf(), substring(), etc.
let str = "Hello"; console.log(str.charAt(1)); // Output: e
Using backticks for string interpolation and multi-line strings.
let name = "Alice"; let age = 25; let greeting = `Hello, my name is ${name} and I am ${age} years old.`; console.log(greeting); // Output: Hello, my name is Alice and I am 25 years old.