Strings

Work with text and common string operations.

Strings are one of the most commonly used data types in JavaScript. A string is a sequence of characters used to represent text. Names, messages, email addresses, product descriptions, and page content are all examples of strings.

What Is a String?

A string is text enclosed within single quotes, double quotes, or backticks.

javascript
let name = "John";
let city = 'Delhi';
let message = `Welcome to JavaScript`;

Creating and Displaying Strings

javascript
let greeting = "Hello World";

console.log(greeting);

Output:

javascript
Hello World

String Length

javascript
let language = "JavaScript";

console.log(language.length);

Output:

javascript
10

Converting Text Case

toUpperCase()

javascript
let name = "john";

console.log(name.toUpperCase());

Output:

javascript
JOHN

toLowerCase()

javascript
let email = "USER@EMAIL.COM";

console.log(email.toLowerCase());

Output:

javascript
user@email.com

Finding Text in a String

includes()

javascript
let message = "Welcome to JavaScript";

console.log(message.includes("JavaScript"));

Output:

javascript
true

indexOf()

javascript
let text = "Hello World";

console.log(text.indexOf("World"));

Output:

javascript
6

Replacing Text

javascript
let message = "Hello John";

let updatedMessage = message.replace("John", "Sarah");

console.log(updatedMessage);

Output:

javascript
Hello Sarah

Extracting Part of a String

javascript
let text = "JavaScript";

console.log(text.slice(0, 4));

Output:

javascript
Java

Template Literals

javascript
let name = "John";

let message = `Hello, ${name}!`;

console.log(message);

Output:

javascript
Hello, John!

Real-World Example

javascript
let username = "john";

console.log(username.toUpperCase());

Output:

javascript
JOHN

Summary

Strings store and manage text in JavaScript. Methods such as length, toUpperCase(), toLowerCase(), includes(), replace(), and slice() make it easy to manipulate text in real web applications.

Let's learn with DevBrainBox AI