Overview of Strings
In JavaScript, a string is a primitive data type used to represent a sequence of characters (text). Strings can be enclosed in single quotes (''), double quotes (""), or backticks (`) for template literals. They are immutable, meaning any operation on a string creates a new string rather than modifying the original. Strings are widely used for storing and manipulating text, such as user input, messages, or data.
- Represented internally as UTF-16 encoded sequences of characters.
- Can include letters, numbers, symbols, and special characters (e.g., emojis).
- Immutable: Operations like
toUpperCase()
orreplace()
return new strings. - Accessible as array-like structures using indices (e.g.,
str[0]
).
String Creation
Strings can be created in three ways:
Single Quotes:
let str = 'Hello';
Double Quotes:
let str = "World";
Template Literals (ES6+, using backticks):
let str = `Hello, World!`;
Common String Methods
JavaScript provides a rich set of built-in methods for string manipulation. Some commonly used methods include:
Length:
Returns the number of characters in a string (property, not a method).
"Hello".length; // 5
Case Conversion:
"Hello".toUpperCase(); // "HELLO"
"World".toLowerCase(); // "world"
Trimming:
" Hello ".trim(); // "Hello"
" Hello".trimStart(); // "Hello"
"Hello ".trimEnd(); // "Hello"
Substring Extraction:
"Hello World".slice(0, 5); // "Hello"
"Hello World".substring(6, 11); // "World"
Replace:
"Hello World".replace("World", "Universe"); // "Hello Universe"
"Hi Hi".replaceAll("Hi", "Hey"); // "Hey Hey"
Splitting and Joining:
"a,b,c".split(","); // ["a", "b", "c"]
["a", "b", "c"].join("-"); // "a-b-c"
Character Access:
"Hello".charAt(0); // "H"
"Hello"[0]; // "H"
"Hello".charCodeAt(0); // 72
Concatenation:
"Hello".concat(" ", "World"); // "Hello World"
"Hello" + " " + "World"; // "Hello World"
Padding:
"5".padStart(3, "0"); // "005"
"5".padEnd(3, "0"); // "500"
Repeating:
"Hi".repeat(3); // "HiHiHi"
String Search & Manipulation
Search Methods:
"Hello World".indexOf("World"); // 6
"Hello Hello".lastIndexOf("Hello"); // 6
"Hello World".includes("World"); // true
"Hello World".startsWith("Hello"); // true
"Hello World".endsWith("World"); // true
Regular Expression Methods:
"Hello123".match(/\\d+/); // ["123"]
"Hello World".search(/\\s/); // 5
"Hello World".replace(/\\s/g, "-"); // "Hello-World"
String Template
String Template (ES6+) use backticks (`) and allow:
- Multi-line strings
- Expression interpolation using
${}
- Tagged templates for custom processing
let name = "World";
let greeting = `Hello, ${name}!`; // "Hello, World!"
let multiLine = `Line 1
Line 2`; // Preserves line breaks
let a = 5, b = 10;
let sum = `Sum: ${a + b}`; // "Sum: 15"
// Tagged template
function tag(strings, ...values) {
return strings[0] + values[0].toUpperCase();
}
tag`Hello, ${name}!`; // "Hello, WORLD!"
String Reference
Operation | Method/Property/Example |
---|---|
Length | str.length → "Hello".length → 5 |
Uppercase | toUpperCase() → "hello".toUpperCase() → "HELLO" |
Lowercase | toLowerCase() → "WORLD".toLowerCase() → "world" |
Trim | trim() → " Hello ".trim() → "Hello" |
Substring | slice(start,end) → "Hello World".slice(0,5) → "Hello" |
Replace | replace(search,new) → "Hi".replace("Hi","Hey") → "Hey" |
Split | split(sep) → "a,b".split(",") → ["a","b"] |
Join (array) | array.join(sep) → ["a","b"].join("-") → "a-b" |
Find Index | indexOf(sub) → "Hello".indexOf("l") → 2 |
Check Substring | includes(sub) → "Hello".includes("lo") → true |
Character Access | charAt(idx) or str[idx] → "Hello"[0] → "H" |
Concatenate | concat(str) or + → "Hello" + " World" → "Hello World" |
Padding | padStart(len,pad) → "5".padStart(3,"0") → "005" |
Repeat | repeat(count) → "Hi".repeat(2) → "HiHi" |
String Template | Hello, ${expr} → Hi, ${"World"} → "Hi, World" |