Strings, Template Literals & Unicode

String আপনি যা ভাবেন তার চেয়ে গভীর — বিশেষত Bangla ও emoji-তে

~35 min Beginner 14 practice problems Live runner

1. Three Quote Styles

quotes.js
const a = 'single';
const b = "double";
const c = `backtick`;     // template literal

const name = "Arif";
console.log(`হ্যালো, ${name}! আজ ${new Date().getFullYear()}.`);

const multi = `first line
second line
third line`;
console.log(multi);
তিনটি quote ধরন — single, double, backtick। Backtick (template literal) সবচেয়ে শক্তিশালী — এতে multi-line এবং ${...} দিয়ে variable interpolation করা যায়।

2. Escape Sequences

EscapeMeaning
\nNewline
\tTab
\\Single backslash
\' \"Quote inside same quote
éUnicode code unit (é)
\u{1F600}Code-point escape (😀)
escape.js
console.log("line1\nline2");
console.log("col\tA\tB");
console.log("He said \"hi\"");
console.log("Café");
console.log("\u{1F600} \u{1F1E7}\u{1F1E9}");

3. Common String Methods

methods.js
const s = "  Hello Bangladesh!  ";

console.log(s.length);                   // 22
console.log(s.trim());                   // "Hello Bangladesh!"
console.log(s.toUpperCase());            // "  HELLO BANGLADESH!  "
console.log(s.includes("Bang"));         // true
console.log(s.indexOf("l"));              // 3
console.log(s.slice(2, 7));               // "Hello"
console.log(s.split(" "));                // ["", "", "Hello", ...]
console.log(s.replace("Bangladesh", "World"));
console.log(s.replaceAll("l", "L"));    // every "l" → "L"
console.log("5".padStart(3, "0"));       // "005"
console.log("abc".repeat(3));            // "abcabcabc"
console.log("abc".at(-1));               // "c"
console.log("hello".startsWith("he"));   // true
console.log("hello".endsWith("lo"));     // true
Strings are immutable None of these methods change the original string — they return new ones. s.toUpperCase() doesn't modify s.

4. Tagged Template Literals

A tag function receives the static parts as an array and the interpolated values as separate arguments. Powerful for sanitization, i18n, and SQL builders.

tagged.js
function highlight(strings, ...values) {
    return strings.reduce((acc, str, i) =>
        acc + str + (values[i] !== undefined ? `[${values[i]}]` : "")
    , "");
}
const name = "Arif";
const age  = 22;
console.log(highlight`Hi ${name}, age ${age}.`);
// "Hi [Arif], age [22]."

5. The UTF-16 Surrogate Trap

JavaScript stores strings as UTF-16 code units. Most characters fit in one unit, but emoji and many scripts (Bangla composed characters, math symbols) require two — so .length can lie about visible characters.

unicode.js
console.log("abc".length);            // 3
console.log("আ".length);              // 1   (single code unit)
console.log("ক্ষ".length);             // 3   (3 code units, 1 grapheme!)
console.log("😀".length);              // 2   (surrogate pair)
console.log("🇧🇩".length);             // 4   (two flag halves)

// Counting code points, not units
console.log([..."😀😀"].length);     // 2  ← spread iterates code points
console.log(Array.from("🇧🇩").length);// 2  ← still not graphemes

// True grapheme count needs Intl.Segmenter (modern)
const seg = new Intl.Segmenter("bn", { granularity: "grapheme" });
console.log([...seg.segment("ক্ষ")].length); // 1
Bangla অক্ষর (যেমন "ক্ষ") দেখতে এক character হলেও কয়েকটি UTF-16 code unit দিয়ে গঠিত হয়। তাই .length দিয়ে user-দৃশ্যমান character count পাওয়া যায় না — সঠিক ভাবে গণনার জন্য Intl.Segmenter ব্যবহার করুন।

6. String.raw & the \ Literal

Use String.raw to keep backslashes intact — handy for regex strings and Windows paths.

raw.js
console.log("a\nb");             // a (newline) b
console.log(String.raw`a\nb`);  // a\nb (literal)
console.log(String.raw`C:\Users\Arif`);

7. Glossary (শব্দকোষ)

TermMeaningবাংলায়
Template literalBacktick string supporting interpolation and multi-line.Backtick দিয়ে লেখা string — variable বসানো ও multi-line দুটোই করা যায়।
InterpolationEmbedding a value inside a string with ${...}.String-এর ভেতরে ${...} দিয়ে value বসানো।
Tagged templateA function that processes a template literal's parts and values.Template literal-কে কাস্টম-ভাবে process করা function।
UTF-16The internal encoding JavaScript uses for strings.JavaScript string-এর ভেতরের encoding।
Code unitOne 16-bit slot in UTF-16 — what .length counts.UTF-16-এর একটি 16-bit slot — .length এটাই গণনা করে।
Code pointOne Unicode character (may need 2 code units).একটি Unicode character (২টি code unit লাগতে পারে)।
Surrogate pairTwo code units representing a code point above U+FFFF.U+FFFF-এর উপরের character-এর জন্য দুটি code unit।
GraphemeWhat a human sees as one character (may be many code points).মানুষের চোখে এক অক্ষর — হতে পারে অনেক code point।
Intl.SegmenterModern API to split text by graphemes/words/sentences.Modern API — grapheme/word/sentence অনুসারে split করে।
মনে রাখবেন: Backtick (template literal) আধুনিক কোডে default — interpolation ও multi-line free। Bangla "ক্ষ"-এর মতো অক্ষর একাধিক UTF-16 code unit হতে পারে, তাই "ক্ষ".length 1 না-ও হতে পারে। সঠিক grapheme count পেতে Intl.Segmenter ব্যবহার করুন। String immutable — সব method নতুন string ফিরিয়ে দেয়, original পরিবর্তন হয় না।

8. Practice Problems

  1. Use a template literal to print "Hello {name}, you have {n} new messages."
    ✨ Show Answer
    a1.js
    const name = "Nusrat", n = 3;
    console.log(`Hello ${name}, you have ${n} new messages.`);
  2. Trim, lowercase, and split this CSV into an array of names: " Arif , Karim, Nusrat ".
    ✨ Show Answer
    a2.js
    const raw = "  Arif , Karim,  Nusrat ";
    const names = raw.split(",").map(s => s.trim().toLowerCase());
    console.log(names); // ["arif","karim","nusrat"]
  3. Reverse a string using spread + reverse + join.
    ✨ Show Answer
    a3.js
    const rev = s => [...s].reverse().join("");
    console.log(rev("hello")); // "olleh"
  4. Count the number of vowels in "Bangladesh".
    ✨ Show Answer
    a4.js
    const count = [..."Bangladesh"].filter(c => "aeiouAEIOU".includes(c)).length;
    console.log(count); // 3
  5. Pad the number 7 on the left with zeros to width 4.
    ✨ Show Answer
    a5.js
    console.log(String(7).padStart(4, "0")); // "0007"
  6. Replace every space in a string with a hyphen.
    ✨ Show Answer
    a6.js
    console.log("hello world today".replaceAll(" ", "-"));
  7. Show that "😀".length is 2 and explain why.
    ✨ Show Answer

    Emojis above U+FFFF are encoded as a "surrogate pair" — two UTF-16 code units. .length counts code units, not code points.

    a7.js
    console.log("😀".length);             // 2
    console.log([..."😀"].length);        // 1
  8. Use Intl.Segmenter to count graphemes in "ক্ষ মা".
    ✨ Show Answer
    a8.js
    const seg = new Intl.Segmenter("bn", { granularity: "grapheme" });
    console.log([...seg.segment("ক্ষ মা")].length);
  9. Build a tag function safe that wraps each interpolated value in <b>...</b>.
    ✨ Show Answer
    a9.js
    function safe(parts, ...vals) {
        return parts.reduce((a, p, i) =>
            a + p + (vals[i] != null ? `<b>${vals[i]}</b>` : ""), "");
    }
    console.log(safe`Hello, ${"Arif"}!`);
  10. Capitalize only the first letter of each word.
    ✨ Show Answer
    a10.js
    const title = s => s.split(" ")
        .map(w => w[0].toUpperCase() + w.slice(1))
        .join(" ");
    console.log(title("hello bangla world"));
  11. Test if a string is a palindrome (case-insensitive, alphanumeric only).
    ✨ Show Answer
    a11.js
    const isPalindrome = s => {
        const clean = s.toLowerCase().replace(/[^a-z0-9]/g, "");
        return clean === [...clean].reverse().join("");
    };
    console.log(isPalindrome("A man, a plan, a canal: Panama"));
  12. Convert "hello-world-today" to camelCase.
    ✨ Show Answer
    a12.js
    const camel = s => s.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
    console.log(camel("hello-world-today")); // "helloWorldToday"
  13. Read a Bangla string and detect whether it contains the letter "ক".
    ✨ Show Answer
    a13.js
    const str = "আমি বাংলাদেশের কথা বলি";
    console.log(str.includes("ক"));
  14. Why does "5" + 3 give "53" but "5" * 3 gives 15?
    ✨ Show Answer

    Answer: The + operator is overloaded — when one operand is a string, it concatenates. The * operator only does numeric multiplication, so it coerces both operands to numbers first. "5" becomes 5 and the result is 15.

    + string-এ থাকলে concat করে; * শুধু সংখ্যা — তাই string-কে number-এ coerce করে।

Summary — Module 07

Use backtick template literals everywhere — they handle multi-line, interpolation, and tag functions. Strings are immutable; methods always return new strings. UTF-16 surprises mean .length ≠ visible character count, especially with emoji and Bangla composed letters. For correct grapheme counting, reach for Intl.Segmenter.

Backtick দিয়ে template literal লিখুন; emoji ও Bangla-তে .length বিভ্রান্তিকর — সঠিক character count পেতে Intl.Segmenter।

Next Module → Numbers, Math & BigInt — কেন 0.1 + 0.2 ≠ 0.3।