JavaScript Fundamentals / Strings

String Methods

🧐 Exploring String Methos

Strings in JavaScript are primitive and immutable, which means their original value cannot be changed after creation. Instead of modifying the existing string, all string methods return a new string with the desired changes while leaving the original string unchanged.


πŸš€ Extracting String Characters

There are 2 commonly used methods:

  • The charAt(position) Method

  • Using property access [ ] like in arrays


βœ… String charAt( )

The charAt() method returns the character at a specified index in a string.

let text = "HELLO";
let char = text.charAt(0);  // H

➑️ Property Access [ ]

  • Works like array indexing: str[0]

  • Read-only, returns undefined if not found

let text = "HELLO";
let char = text[0];  // H

πŸš€ Extracting String Parts

♦️ String slice( )

  • slice(start, end) returns part of the string

  • Supports negative indexes

  • End index is not included

let text = "Apple, Banana, Kiwi";
let part = text.slice(7, 13);   // Banana

πŸš€ Changing Case

πŸŽ—οΈ String toUpperCase( )

Converts string to uppercase.

let text = "Hello";
let result = text.toUpperCase();  // HELLO

πŸ–‡οΈ String toLowerCase( )

Converts string to lowercase.

let text = "Hello";
let result = text.toLowerCase();  // hello

πŸš€ String Concatenation

πŸ”° Using + or concat( )

You can join strings using either:

let text1 = "Hello";
let text2 = "World";
let text3 = text1 + " " + text2;   // Hello World
let text3 = text1.concat(" ", text2);   // Hello World

πŸš€ Trimming Whitespace

βœ”οΈ String trim( )

Removes whitespace from both ends of the string.

let text = "   Hello World!   ";
let result = text.trim();   // "Hello World!"

πŸš€ Replacing and Repeating

▢️ String replace( )

Replaces the first occurrence of a match.

let text = "Please visit Microsoft!";
let newText = text.replace("Microsoft", "Codeveda"); // "Please visit Codeveda"

🧩 String replaceAll( )

Replaces all occurrences in a string.

let text = "I love cats. Cats are great.";
let newText = text.replaceAll("Cats", "Dogs"); // I love Dogs. Dogs are great"

πŸ“š String repeat( )

Repeats a string multiple times.

let text = "Hi! ";
let result = text.repeat(3);  // Hi! Hi! Hi!

πŸš€ Searching Strings

πŸ“ String includes( )

Checks if a string contains the given text.

let text = "Hello world";
text.includes("world");  // true

πŸͺ„ String startsWith( ) & endsWith( )

  • startsWith() – checks if a string starts with specified text

  • endsWith() – checks if it ends with specified text

let text = "Hello world";
text.startsWith("Hello");  // true
text.endsWith("world");    // true