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 WorldString Length
javascript
let language = "JavaScript";
console.log(language.length);Output:
javascript
10Converting Text Case
toUpperCase()
javascript
let name = "john";
console.log(name.toUpperCase());Output:
javascript
JOHNtoLowerCase()
javascript
let email = "USER@EMAIL.COM";
console.log(email.toLowerCase());Output:
javascript
user@email.comFinding Text in a String
includes()
javascript
let message = "Welcome to JavaScript";
console.log(message.includes("JavaScript"));Output:
javascript
trueindexOf()
javascript
let text = "Hello World";
console.log(text.indexOf("World"));Output:
javascript
6Replacing Text
javascript
let message = "Hello John";
let updatedMessage = message.replace("John", "Sarah");
console.log(updatedMessage);Output:
javascript
Hello SarahExtracting Part of a String
javascript
let text = "JavaScript";
console.log(text.slice(0, 4));Output:
javascript
JavaTemplate 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
JOHNSummary
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.