JavaScript Strings Explained

📌 What is a String?

A string is a sequence of characters used to represent text in programming. In JavaScript, strings are enclosed in either 'single quotes', "double quotes", or `template literals`.

let message = "Hello, world!";
let name = 'Rohan';
let greeting = `Hello, ${name}`;

✅ Why Use Strings?

📍 Where Are Strings Used?

🧠 Common String Methods (with Examples)

Know more in Detail

1. length

Returns the number of characters in a string.

let str = "Hello";
console.log(str.length); // 5

2. toUpperCase() / toLowerCase()

Converts a string to upper or lower case.

let city = "delhi";
console.log(city.toUpperCase()); // "DELHI"

3. includes()

Checks if a substring is present in a string. Returns true or false.

let email = "user@example.com";
console.log(email.includes("@")); // true

4. indexOf()

Returns the index of the first occurrence of a specified value.

let text = "JavaScript";
console.log(text.indexOf("S")); // 4

5. slice(start, end)

Extracts a section of a string and returns it as a new string.

let lang = "JavaScript";
console.log(lang.slice(0, 4)); // "Java"

6. replace()

Replaces a value with another in a string.

let text = "I like HTML";
console.log(text.replace("HTML", "JavaScript")); // "I like JavaScript"

7. trim()

Removes whitespace from both ends of a string.

let name = "   Rohan   ";
console.log(name.trim()); // "Rohan"

8. split()

Splits a string into an array of substrings.

let fruits = "apple,banana,grape";
console.log(fruits.split(",")); // ["apple", "banana", "grape"]

9. charAt()

Returns the character at a specified index.

let str = "Rohan";
console.log(str.charAt(2)); // "p"

10. concat()

Joins two or more strings.

let fname = "Rohan";
let lname = "Kumar";
console.log(fname.concat(" ", lname)); // "Rohan Kumar"

🔗 References