learn2kode.in

JavaScript Strings

A string in JavaScript is used to store text data. Strings can include letters, numbers, symbols, and spaces.

Creating Strings

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).

String Length

Use .length to find the number of characters.

let text = "JavaScript";
console.log(text.length); // 10
Accessing Characters

Characters are accessed using index numbers (starting from 0).

let word = "Hello";
console.log(word[0]); // H
console.log(word[4]); // o
Changing Case
let text = "Learn JavaScript";

text.toUpperCase(); // "LEARN JAVASCRIPT"
text.toLowerCase(); // "learn javascript"
Removing Extra Spaces
let input = "  Hello World  ";
input.trim(); // "Hello World"
Finding Text

includes()

let msg = "JavaScript is powerful";
msg.includes("powerful"); // true

indexOf()

msg.indexOf("Script"); // 4
Replacing Text
let sentence = "I love HTML";
sentence.replace("HTML", "JavaScript");
// "I love JavaScript"
Extracting Parts of Strings

slice()

let text = "JavaScript";
text.slice(0, 4); // "Java"

substring()

text.substring(4, 10); // "Script"
Splitting Strings
let skills = "HTML,CSS,JavaScript";
skills.split(",");
// ["HTML", "CSS", "JavaScript"]
Joining Strings

Using +

let first = "Hello";
let last = "World";

first + " " + last; // "Hello World"
Using Template Literals (Recommended)
let name = "John";
`Hello ${name}`; // "Hello John"
Checking Start & End
let file = "index.html";

file.startsWith("index"); // true
file.endsWith(".html");   // true
Useful String Methods
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 in Real Projects

Strings are commonly used for:

Key Takeaways