Friday, June 27, 2025

Javascript Module 19

  Module 19 : String Methods and Template Literals.

๐Ÿง  ๐Ÿ“˜ 1. Introduction to JavaScript Strings


















A string is a sequence of characters used to represent text. In JavaScript, strings are immutable—once created, they cannot be changed directly.

Declaring Strings:

javascript

code

let name = "Reha"; let greeting = 'Hello'; let multiline = `This is a multiline string.`;


๐Ÿ” 2. String Methods in JavaScript

JavaScript provides a rich set of built-in string methods. Below is a categorized breakdown.

๐Ÿ”ค A. Basic Methods

Method

Description

Example

length

Returns the number of characters

"Hello".length → 5

charAt(index)

Returns character at the specified index

"Hello".charAt(1) → 'e'

charCodeAt(i)

Returns UTF-16 code of character at index

"A".charCodeAt(0) → 65



๐Ÿงฑ B. Searching Methods

Method

Description

Example

indexOf(substr)

Returns the first index of a substring

"banana".indexOf("a") → 1

lastIndexOf(substr)

Returns last index

"banana".lastIndexOf("a") → 5

includes(substr)

Returns true if substring exists

"hello".includes("ell") → true

startsWith(substr)

Checks if string starts with a substring

"hello".startsWith("he") → true

endsWith(substr)

Checks if string ends with a substring

"hello".endsWith("lo") → true



๐Ÿ› ️ C. Manipulation Methods

            


Method

Description

Example

toUpperCase()

Converts string to uppercase

"abc".toUpperCase() → "ABC"

toLowerCase()

Converts string to lowercase

"ABC".toLowerCase() → "abc"

trim()

Removes whitespace from both ends

" hello ".trim() → "hello"

slice(start, end)

Extracts part of string

"abcdef".slice(2, 4) → "cd"

substring(start, end)

Similar to slice, doesn't accept negatives

"abcdef".substring(2, 4) → "cd"

substr(start, length)

Deprecated, but still in use

"abcdef".substr(2, 3) → "cde"

replace(old, new)

Replaces first occurrence

"dog".replace("d", "f") → "fog"

replaceAll(old, new)

Replaces all occurrences

"a-a-a".replaceAll("a", "b") → "b-b-b"

repeat(n)

Repeats string n times

"ha".repeat(3) → "hahaha"

split(separator)

Splits string into array

"a,b,c".split(",") → ["a","b","c"]

concat(str)

Concatenates strings

"hi".concat(" there") → "hi there"



๐Ÿงฉ 3. Template Literals

Template literals are a modern ES6 feature using backticks (`). They allow:

Multiline strings

String interpolation

Expression embedding

๐Ÿ“Œ Syntax:

javascript

 code

let name = "Rehana"; let message = `Hello, ${name}! Welcome to JavaScript.`; console.log(message);

๐Ÿ” Template Literals Features:

Multiline:

javascript

code

let poem = `Roses are red, Violets are blue.`;

Embedded Expressions:

javascript

 code

let a = 5, b = 10; console.log(`Sum is: ${a + b}`);


๐Ÿงช 4.  Exercises

✅ Exercise 1: Capitalize the First Letter of a String

javascript

code

function capitalize(str) { return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase(); } console.log(capitalize("javascript")); // Output: Javascript

✅ Exercise 2: Count Occurrences of a Character

             


javascript

 code

function countChar(str, char) { return str.split(char).length - 1; } console.log(countChar("banana", "a")); // Output: 3

✅ Exercise 3: Create a Dynamic Message Using Template Literals

javascript

code

let username = "Rehana"; let tasks = 5; let msg = `Hello ${username}, you have ${tasks} pending tasks today.`; console.log(msg);


๐Ÿงช 5.๐Ÿ”ฌ  Build a String Formatter Utility

Create a utility that accepts a user input string and provides the following:

Total characters (excluding spaces).

Number of words.

First and last characters.

Sentence capitalized.

Reformat using template literals.

๐Ÿง‘‍๐Ÿ’ป Sample Code:

javascript

 code

function stringStats(input) { let cleaned = input.trim(); let words = cleaned.split(" "); let wordCount = words.length; let charCount = cleaned.replace(/\s/g, '').length; return ` Input Summary: ---------------------- Original: "${input}" Characters (no spaces): ${charCount} Words: ${wordCount} First Character: ${cleaned.charAt(0)} Last Character: ${cleaned.charAt(cleaned.length - 1)} Capitalized: ${cleaned.charAt(0).toUpperCase() + cleaned.slice(1)} `; } console.log(stringStats(" hello world from JavaScript "));


๐Ÿ”ฌ 6. Based Insights for Understanding

            


๐Ÿ“Œ 1: Why Strings Are Immutable in JavaScript

JavaScript strings are immutable for performance and security reasons. Instead of modifying strings directly, a new string is created, reducing memory management issues and bugs due to unintended side effects.

๐Ÿ“Œ 2: String Interning in JavaScript Engines

Modern JS engines like V8 (Chrome) or SpiderMonkey (Firefox) optimize string usage by interning—storing identical strings in memory only once—saving performance.

๐Ÿ“Œ Insight 3: Template Literals vs. Traditional Concatenation

Studies show that template literals:

Improve code readability

Reduce syntax errors

Perform comparably to concatenation in most cases

Example:

javascript

code

// Traditional Concatenation let result = "Hello " + name + ", your score is " + score + "."; // Template Literal let result = `Hello ${name}, your score is ${score}.`;


๐Ÿง  7. Review Questions

What is the difference between slice() and substring()?

How would you extract the last 3 characters of a string?

Write a function to reverse a string using built-in methods.

What are the benefits of template literals over string concatenation?


๐Ÿง‘‍๐Ÿซ 8. Assignment

Build a string-based data parser that:

Accepts a user bio string input.

Extracts first name, last name, and age.

Formats the data using a template literal for a profile card.


✅ 9. Summary

Explored core and advanced string methods.

           


Mastered template literals for clean, modern syntax.

Completed exercises.

Gained insight into JavaScript engine optimizations and best practices.

 10. Further

MDN String Reference

JavaScript Info: Strings

V8 Engine Optimization Tips


No comments:

Post a Comment

Javascript Module 20

  Javascript Module 20 If You want To Earn Certificate For My  All   Course Then Contact Me At My  Contact  Page   then I Will Take A Test A...