JS Strings

Overview

Strings in JavaScript are sequences of characters enclosed within single ('') or double ("") quotes. They are essential for representing textual data and are extensively used in programming for text manipulation, output formatting, and more.


Creating Strings

Strings can be created using single or double quotes.

Try yourself
        
            let singleQuotes = 'This is a string.';
let doubleQuotes = "Another string.";
        
    

String Concatenation

Strings can be concatenated using the + operator.

Try yourself
        
            let firstName = "John";
let lastName = "Doe";
let fullName = firstName + " " + lastName;   // John Doe

console.log(fullName) // John Doe
        
    

Escape Characters

Special characters can be included in strings using escape sequences.

Try yourself
        
            let text = "This is a \"quote\" inside a string.";

console.log(text) // This is a "quote" inside a string.

        
    

String Methods

Try yourself
        
            let text = "   Hello, world!   ";
let trimmedStart = text.trimStart();      // "Hello, world!   "
let trimmedEnd = text.trimEnd();          // "   Hello, world!"
let paddedStart = text.padStart(20, "-"); // "-----   Hello, world!   "
let paddedEnd = text.padEnd(20, "-");     // "   Hello, world!   -----"
let character = text.charAt(7);           // "w"
let unicodeValue = text.charCodeAt(7);    // 119
let replacedText = text.replace("world", "Universe");  // "   Hello, Universe!   "
let uppercaseText = text.toUpperCase();   // "   HELLO, WORLD!   "

console.log(text)
console.log(trimmedStart)
console.log(trimmedEnd)
console.log(paddedStart)
console.log(paddedEnd)
console.log(character)
console.log(unicodeValue)
console.log(replacedText)
console.log(uppercaseText)
        
    

Template Literals (``)

Template literals allow string interpolation and multiline strings.

Try yourself
        
            let name = "Alice";
let age = 30;
let greeting = `Hello, ${name}! You are ${age} years old.`;

console.log(greeting) // Hello, Alice! You are 30 years old.
        
    

Summary

Strings are fundamental data types in JavaScript used to represent text. With various methods and operations available, strings are versatile tools for text manipulation, formatting, and more.