Loading...

Go Back

Next page
Go Back Course Outline

JavaScript Full Course


Strings in JavaScript

A string is a sequence of characters used to represent text. In JavaScript, strings are written inside single quotes (''), double quotes (""), or backticks (``) for template literals.

Creating Strings:
const name = "Alice";
const greeting = 'Hello';
const message = `Welcome, ${name}!`; // Template literal
Common String Methods:
  • length – Returns the number of characters
  • toUpperCase() – Converts to uppercase
  • toLowerCase() – Converts to lowercase
  • charAt(index) – Returns the character at a specific index
  • includes(substring) – Checks if a substring exists
  • indexOf(substring) – Returns the position of a substring
  • replace(old, new) – Replaces part of the string
  • slice(start, end) – Extracts part of a string
  • trim() – Removes whitespace from both ends
Example:
const text = "  JavaScript is fun!  ";

console.log(text.length);           // 22
console.log(text.trim());           // "JavaScript is fun!"
console.log(text.toUpperCase());    // "  JAVASCRIPT IS FUN!  "
console.log(text.includes("fun"));  // true
Template Literals:

Use backticks ` and ${} to embed variables:

const name = "Bob";
const message = `Hello, ${name}!`;
console.log(message); // Output: Hello, Bob!
Tip:

Strings are one of the most used data types in JavaScript. Use string methods to clean, format, and manipulate text easily.

1. String Literals

Creating strings using single, double quotes, or backticks.

                        let str1 = 'Hello, world!';
                        let str2 = "Hello, world!";
                        let name = `John`;
                        console.log(str1, str2, name);  // Output: Hello, world! Hello, world! John
                                
Output:
Hello, world! Hello, world! John


2. String Methods

Using string methods like charAt(), indexOf(), substring(), etc.

2.1 charAt()

                        let str = "Hello";
                        console.log(str.charAt(1));  // Output: e
                                
Output:
e


3. Template Literals

Using backticks for string interpolation and multi-line strings.

                        let name = "Alice";
                        let age = 25;
                        let greeting = `Hello, my name is ${name} and I am ${age} years old.`;
                        console.log(greeting);  // Output: Hello, my name is Alice and I am 25 years old.
                                
Output:
Hello, my name is Alice and I am 25 years old.
Go Back

Next page