A string in JavaScript is used to store text data. Strings can include letters, numbers, symbols, and spaces.
Strings can be created using single quotes, double quotes, or backticks.
let name = "John";
let city = 'London';
let message = `Welcome to Learn2Kode`;
Backticks allow template literals (used heavily in modern JavaScript and React).
Use .length to find the number of characters.
let text = "JavaScript";
console.log(text.length); // 10
Characters are accessed using index numbers (starting from 0).
let word = "Hello";
console.log(word[0]); // H
console.log(word[4]); // o
let text = "Learn JavaScript";
text.toUpperCase(); // "LEARN JAVASCRIPT"
text.toLowerCase(); // "learn javascript"
let input = " Hello World ";
input.trim(); // "Hello World"
includes()
let msg = "JavaScript is powerful";
msg.includes("powerful"); // true
indexOf()
msg.indexOf("Script"); // 4
let sentence = "I love HTML";
sentence.replace("HTML", "JavaScript");
// "I love JavaScript"
slice()
let text = "JavaScript";
text.slice(0, 4); // "Java"
substring()
text.substring(4, 10); // "Script"
let skills = "HTML,CSS,JavaScript";
skills.split(",");
// ["HTML", "CSS", "JavaScript"]
Using +
let first = "Hello";
let last = "World";
first + " " + last; // "Hello World"
let name = "John";
`Hello ${name}`; // "Hello John"
let file = "index.html";
file.startsWith("index"); // true
file.endsWith(".html"); // true
| Method | Purpose | Example |
|---|---|---|
| length | Count characters | text.length |
| toUpperCase() | Convert to uppercase | text.toUpperCase() |
| toLowerCase() | Convert to lowercase | text.toLowerCase() |
| trim() | Remove spaces | text.trim() |
| includes() | Check text | text.includes("js") |
| replace() | Replace text | text.replace("a","b") |
| split() | Convert to array | text.split(",") |
Strings are commonly used for: