JavaScript Strings: Methods, Immutability & Modern Template Literals

In JavaScript, a String is an immutable sequence of 16-bit Unicode characters used to represent and manipulate text. Strings can be instantiated using single quotes ('...'), double quotes ("..."), or modern ES6 backticks (`...`).

String Immutability: A Foundational Concept

In JavaScript, strings are immutable primitives. Once a string value is allocated in memory, its characters can never be overwritten or mutated in-place:

let city = "Delhi";
city[0] = "J"; // Trying to mutate 'D' to 'J'
console.log(city); // Output: "Delhi" (Unchanged!)

// Any operation produces a BRAND NEW string in memory:
let updatedCity = "New " + city;
console.log(updatedCity); // "New Delhi"

Essential JavaScript String Methods (Quick Reference Table)

Method Description Code Example & Returned Output
length (Property) Returns total character count. "Veewom".length === 6
slice(start, end) Extracts section; supports negative indices. "JavaScript".slice(0, 4) === "Java"
"Hello".slice(-2) === "lo"
includes(substr) Checks if substring exists (boolean). "Frontend".includes("end") === true
indexOf(substr) Returns first index position, or -1. "apple".indexOf("p") === 1
trim() / trimStart() Removes whitespace from both ends. " admin ".trim() === "admin"
replace() / replaceAll() Replaces matching patterns/regex. "cat dog cat".replaceAll("cat", "cow")
split(delimiter) Splits string into array of substrings. "HTML,CSS,JS".split(",") === ["HTML","CSS","JS"]
toUpperCase() / toLowerCase() Converts entire string case. "hello".toUpperCase() === "HELLO"

Modern ES6 Template Literals (String Interpolation)

Prior to ES6, building dynamic strings required awkward, error-prone string concatenation with + operators. Template literals use backticks (`) to deliver elegant interpolation:

const studentName = "Vikram Aditya";
const semester = 4;
const cgpa = 9.4;

// 1. String Interpolation with ${expression}
const reportCard = `Student ${studentName} enrolled in Semester ${semester} achieved a CGPA of ${cgpa}.`;
console.log(reportCard);

// 2. Multi-line Strings (Preserves formatting without \n)
const htmlSnippet = `
<div class="student-card">
    <h3>${studentName}</h3>
    <p>Status: ${cgpa >= 7.5 ? "First Class with Distinction" : "Pass"}</p>
</div>
`;
console.log(htmlSnippet);

University Exam Corner (BCA Semester Exam)

Exam Question: "Write a JavaScript function to check whether a given string is a Palindrome (reads same forwards and backwards)."

function isPalindrome(str) {
    // 1. Sanitize: remove non-alphanumeric chars & convert to lowercase
    const cleanStr = str.toLowerCase().replace(/[^a-z0-9]/g, "");
    
    // 2. Reverse string using split -> reverse -> join
    const reversedStr = cleanStr.split("").reverse().join("");
    
    // 3. Compare original with reversed
    return cleanStr === reversedStr;
}

console.log(isPalindrome("A man, a plan, a canal: Panama")); // true
console.log(isPalindrome("Veewom")); // false

Next Step

How do you package reusable blocks of logic and manage parameters? Proceed to: JavaScript Functions & Arrow Syntax →

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!