A string in JavaScript is a sequence of characters used to represent text.
const message = "Hello, world!";
const name = 'John Doe';Strings can be written using:
" "' '` `let greeting = "Good morning";
let city = 'Mumbai';
let message = `Welcome, user!`;const msg = "Hello";
console.log(msg.length); // 5You can access characters using index (starting from 0):
const word = "JavaScript";
console.log(word[0]); // J
console.log(word.charAt(4)); // Sconst text = "Learn JavaScript";
console.log(text.toUpperCase()); // LEARN JAVASCRIPT
console.log(text.toLowerCase()); // learn javascript| Method | Description | Example |
|---|---|---|
length | Returns length | str.length |
toUpperCase() | Converts to uppercase | "hello".toUpperCase() → "HELLO" |
toLowerCase() | Converts to lowercase | "HELLO".toLowerCase() → "hello" |
includes() | Checks if string contains text | "abc".includes("b") → true |
indexOf() | Finds position of first occurrence | "banana".indexOf("a") → 1 |
lastIndexOf() | Finds position of last occurrence | "banana".lastIndexOf("a") → 5 |
startsWith() | Checks if string starts with given text | "hello".startsWith("he") → true |
endsWith() | Checks if string ends with given text | "hello".endsWith("o") → true |
slice(start, end) | Extracts part of string | "abcdef".slice(1, 4) → "bcd" |
substring() | Similar to slice | "hello".substring(0, 2) → "he" |
replace() | Replaces first match | "I love cats".replace("cats", "dogs") |
trim() | Removes whitespace | " hello ".trim() → "hello" |
split() | Splits string into array | "a,b,c".split(",") → ["a", "b", "c"] |
concat() | Joins two strings | "Hi".concat(" there") → "Hi there" |
Template literals use backticks (` `) to support:
${}const name = "Amit";
const greeting = `Hello, ${name}!`;
console.log(greeting); // Hello, Amit!const fullMessage = `
Dear Student,
Your result is ready.
Regards,
Admin
`;
console.log(fullMessage);Use \ (backslash) to escape special characters:
const quote = "He said, \"Let's go!\"";Other escape sequences:
\n - New line\t - Tab\\ - BackslashStrings can be compared alphabetically using ==, ===, <, >:
console.log("apple" < "banana"); // true
console.log("A" < "a"); // true (uppercase comes before lowercase)Strings are immutable — you can't change a character directly:
let msg = "hello";
msg[0] = "H"; // ❌ Invalid
msg = "Hello"; // ✅ Correct waya appears using .split() and .length.slice() to extract the first name from a full name." Welcome! " to "welcome!" (trim + lowercase).Hello, [Your Name]!
Welcome to JavaScript Strings.