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