String Basics
Learn how to create and work with strings in JavaScript.
String Basics
A string is simply text. Any sequence of characters — letters, numbers, symbols, spaces — wrapped in quotes is a string.
const name = "Ali";
const city = 'Lahore';
const message = `Hello, world!`;You have been using strings since the very first topic. Now let's go deeper — how they work, how to create them, and the important behaviors you need to know.
Three Ways to Create a String
JavaScript has three types of quotes for strings — all valid, each with a specific purpose.
Double quotes ""
const name = "Ali Hassan";
const message = "Hello, welcome to DocsHub!";Single quotes ''
const city = 'Lahore';
const country = 'Pakistan';Double and single quotes work identically. The only reason to pick one over the other is consistency — pick one style and stick with it across your project.
Backticks `` — Template Literals
const greeting = `Hello, ${name}!`;Backticks are special. They let you embed expressions directly into the string and support multiple lines. We cover them in full detail in the Template Literals topic.
Mixing quotes
If your string contains one type of quote, wrap it in the other type:
const sentence1 = "It's a great day!"; // single quote inside double quotes
const sentence2 = 'He said "hello".'; // double quote inside single quotesOr use a backslash to escape the quote:
const sentence3 = "It\"s a great day!"; // escaped double quote
const sentence4 = 'He said \'hello\'.'; // escaped single quoteUsing the other quote type is cleaner — escape only when you have no choice.
Strings Are Immutable
Once a string is created, it cannot be changed. String methods always return a new string — they never modify the original.
const name = "ali";
const upper = name.toUpperCase();
console.log(name); // ali — unchanged
console.log(upper); // ALI — new stringIf you want to update a string variable, you reassign it:
let greeting = "hello";
greeting = greeting + " world";
console.log(greeting); // hello worldString Length
The length property gives you the number of characters in a string.
const name = "Ali";
console.log(name.length); // 3
const empty = "";
console.log(empty.length); // 0
const sentence = "Hello, world!";
console.log(sentence.length); // 13Spaces and punctuation count as characters too.
Accessing Characters
Strings work like arrays of characters — each character has an index starting at 0.
const name = "Ali";
// 0 1 2
console.log(name[0]); // A
console.log(name[1]); // l
console.log(name[2]); // i
console.log(name[3]); // undefined — no character at index 3Use .at() for negative indexes — same as arrays:
const word = "JavaScript";
console.log(word.at(0)); // J — first character
console.log(word.at(-1)); // t — last character
console.log(word.at(-4)); // r — fourth from the endStrings are read-only by index — you cannot change a character this way:
let name = "Ali";
name[0] = "X"; // silently fails — strings are immutable
console.log(name); // Ali — unchangedEscape Characters
Some characters cannot be typed directly into a string. Use a backslash \ followed by a special character code.
console.log("First line\nSecond line");
// First line
// Second line
console.log("Name:\tAli");
// Name: Ali
console.log("She said \"hello\".");
// She said "hello".
console.log("C:\\Users\\Ali");
// C:\Users\Ali| Escape | Result |
|---|---|
\n | New line |
\t | Tab |
\\ | Backslash |
\" | Double quote |
\' | Single quote |
String Concatenation
Joining strings together is called concatenation. The + operator does this.
const firstName = "Ali";
const lastName = "Hassan";
const fullName = firstName + " " + lastName;
console.log(fullName); // Ali Hassanconst greeting = "Hello, " + firstName + "! Welcome to DocsHub.";
console.log(greeting); // Hello, Ali! Welcome to DocsHub.This works — but template literals are much cleaner for this. We cover them in the Template Literals topic. String concatenation with + is mainly seen in older code.
Strings and Numbers
When you use + with a string and a number, JavaScript converts the number to a string and concatenates — not adds.
console.log("Score: " + 100); // "Score: 100"
console.log("Page " + 1 + 2); // "Page 12" — not "Page 3"
console.log("Page " + (1 + 2)); // "Page 3" — parentheses force addition firstWe covered this in detail in the Type Coercion topic. Always be intentional when mixing strings and numbers with +.
Converting to String
Three ways to convert other values to strings:
// String() function
console.log(String(42)); // "42"
console.log(String(true)); // "true"
console.log(String(null)); // "null"
console.log(String([1,2,3])); // "1,2,3"
// .toString() method
console.log((42).toString()); // "42"
console.log((255).toString(16)); // "ff" — hexadecimal
console.log((8).toString(2)); // "1000" — binary
// Template literal
const age = 22;
console.log(`${age}`); // "22"Converting From String
Parse a string into a number when you need to do math:
const input = "42";
console.log(Number(input)); // 42
console.log(parseInt(input)); // 42 — integer only
console.log(parseFloat("3.14")); // 3.14
// parseInt stops at the first non-numeric character
console.log(parseInt("42px")); // 42 — useful for CSS values
console.log(parseInt("abc")); // NaNChecking Content
typeof for strings
console.log(typeof "Ali"); // "string"
console.log(typeof 42); // "number"Comparing strings
Strings compare character by character using Unicode values. Uppercase letters come before lowercase in Unicode.
console.log("apple" === "apple"); // true
console.log("apple" === "Apple"); // false — case sensitive
console.log("apple" < "banana"); // true — a comes before b
console.log("b" > "a"); // trueFor case-insensitive comparison, convert both to the same case first:
const input = "Ali";
const stored = "ali";
console.log(input.toLowerCase() === stored.toLowerCase()); // trueA Real Example — Name Formatter
function formatName(raw) {
const trimmed = raw.trim(); // remove extra spaces
const lower = trimmed.toLowerCase(); // all lowercase
const parts = lower.split(" "); // split into words
const formatted = parts
.map(part => part[0].toUpperCase() + part.slice(1)) // capitalize each word
.join(" ");
return formatted;
}
console.log(formatName(" ali hassan ")); // Ali Hassan
console.log(formatName("SARA KHAN")); // Sara Khan
console.log(formatName("zara Ahmed")); // Zara AhmedThis pulls together several string concepts — trim(), toLowerCase(), split(), index access, slice(), and join(). We cover all these methods in full in the next topic.
Summary
- Strings are text — created with
"",'', or backticks - Use double/single quotes interchangeably — use backticks for template literals
- Strings are immutable — methods return new strings, never modify the original
- Access characters by index starting at
0— use.at(-1)for the last character lengthproperty gives the number of characters- Escape special characters with
\—\nfor newline,\tfor tab +with strings concatenates — be careful mixing with numbers- Convert to string with
String(),.toString(), or template literals - Convert from string with
Number(),parseInt(),parseFloat() - String comparison is case-sensitive — use
.toLowerCase()for case-insensitive checks