JavaScript Strings
What is a String?
In JavaScript, a string is a sequence of characters used to represent text. Strings are enclosed either in:
- Single quotes ' '
- Double quotes " "
- Backticks ` ` (Template Literals)
How to Create a String?
You can create a string in two ways:
1. Using String Literals
let name = "John";
let city = 'New York';
2. Using the String Object
let greeting = new String("Hello World");
Tip: Prefer string literals because they are simpler and faster.
Examples and Outputs
Example 1: Single and Double Quotes
let str1 = 'Hello';
let str2 = "World";
console.log(str1); // Output: Hello
console.log(str2); // Output: World
Example 2: Using Quotes Inside Strings
You can use opposite quotes inside:
let str3 = "It's a beautiful day";
let str4 = 'He said, "Hello!"';
console.log(str3); // Output: It's a beautiful day
console.log(str4); // Output: He said, "Hello!"
If needed, you can also use escape characters:
let str5 = 'It\'s a beautiful day';
let str6 = "He said, \"Hello!\"";
console.log(str5); // Output: It's a beautiful day
console.log(str6); // Output: He said, "Hello!"
String Properties
- length — Returns the length of the string.
let str = "JavaScript";
console.log(str.length); // Output: 10
Common String Methods
Method | Description | Example | Output |
---|---|---|---|
toUpperCase() | Converts to uppercase | "hello".toUpperCase() | HELLO |
toLowerCase() | Converts to lowercase | "HELLO".toLowerCase() | hello |
includes() | Checks if substring exists | "JavaScript".includes("Script") | true |
indexOf() | Finds position of substring | "JavaScript".indexOf("Script") | 4 |
slice(start, end) | Extracts part of string | "JavaScript".slice(0, 4) | Java |
replace(old, new) | Replaces part of string | "Hello World".replace("World", "JS") | Hello JS |
trim() | Removes spaces | " Hello ".trim() | Hello |
Template Literals (Backticks)
Template literals allow:
- Multi-line strings
- String interpolation (inserting variables)
let name = "Alice";
let greeting = `Hello, ${name}!`;
console.log(greeting); // Output: Hello, Alice!
Multi-line example:
let message = `This is
a multi-line
string.`;
console.log(message);
// Output:
// This is
// a multi-line
// string.
Escape Characters
Sometimes you need special characters inside strings:
Escape Sequence | Meaning | Example | Output |
---|---|---|---|
\' | Single quote | 'It\'s sunny' | It's sunny |
\" | Double quote | "He said \"Hi\"" | He said "Hi" |
\\ | Backslash | "C:\\path\\to\\file" | C:\path\to\file |
\n | New line | "Hello\nWorld" | Hello
World |
\t | Tab space | "Hello\tWorld" | Hello World |
Quick Recap
- A string holds text.
- Use " ", ' ', or ` ` to define strings.
- .length, .toUpperCase(), .slice() are common methods.
- Template literals (`) make dynamic text easy.