Strings, Template Literals & Unicode
String আপনি যা ভাবেন তার চেয়ে গভীর — বিশেষত Bangla ও emoji-তে
1. Three Quote Styles
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);
${...} দিয়ে variable interpolation করা যায়।2. Escape Sequences
| Escape | Meaning |
|---|---|
\n | Newline |
\t | Tab |
\\ | Single backslash |
\' \" | Quote inside same quote |
é | Unicode code unit (é) |
\u{1F600} | Code-point escape (😀) |
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
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
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.
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.
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
"ক্ষ") দেখতে এক 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.
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 (শব্দকোষ)
| Term | Meaning | বাংলায় |
|---|---|---|
| Template literal | Backtick string supporting interpolation and multi-line. | Backtick দিয়ে লেখা string — variable বসানো ও multi-line দুটোই করা যায়। |
| Interpolation | Embedding a value inside a string with ${...}. | String-এর ভেতরে ${...} দিয়ে value বসানো। |
| Tagged template | A function that processes a template literal's parts and values. | Template literal-কে কাস্টম-ভাবে process করা function। |
| UTF-16 | The internal encoding JavaScript uses for strings. | JavaScript string-এর ভেতরের encoding। |
| Code unit | One 16-bit slot in UTF-16 — what .length counts. | UTF-16-এর একটি 16-bit slot — .length এটাই গণনা করে। |
| Code point | One Unicode character (may need 2 code units). | একটি Unicode character (২টি code unit লাগতে পারে)। |
| Surrogate pair | Two code units representing a code point above U+FFFF. | U+FFFF-এর উপরের character-এর জন্য দুটি code unit। |
| Grapheme | What a human sees as one character (may be many code points). | মানুষের চোখে এক অক্ষর — হতে পারে অনেক code point। |
Intl.Segmenter | Modern API to split text by graphemes/words/sentences. | Modern API — grapheme/word/sentence অনুসারে split করে। |
"ক্ষ".length 1 না-ও হতে পারে। সঠিক grapheme count পেতে Intl.Segmenter ব্যবহার করুন। String immutable — সব method নতুন string ফিরিয়ে দেয়, original পরিবর্তন হয় না।
8. Practice Problems
- Use a template literal to print "Hello {name}, you have {n} new messages."
✨ Show Answer
a1.jsconst name = "Nusrat", n = 3; console.log(`Hello ${name}, you have ${n} new messages.`); - Trim, lowercase, and split this CSV into an array of names:
" Arif , Karim, Nusrat ".✨ Show Answer
a2.jsconst raw = " Arif , Karim, Nusrat "; const names = raw.split(",").map(s => s.trim().toLowerCase()); console.log(names); // ["arif","karim","nusrat"] - Reverse a string using spread + reverse + join.
✨ Show Answer
a3.jsconst rev = s => [...s].reverse().join(""); console.log(rev("hello")); // "olleh" - Count the number of vowels in
"Bangladesh".✨ Show Answer
a4.jsconst count = [..."Bangladesh"].filter(c => "aeiouAEIOU".includes(c)).length; console.log(count); // 3 - Pad the number
7on the left with zeros to width 4.✨ Show Answer
a5.jsconsole.log(String(7).padStart(4, "0")); // "0007" - Replace every space in a string with a hyphen.
✨ Show Answer
a6.jsconsole.log("hello world today".replaceAll(" ", "-")); - Show that
"😀".lengthis 2 and explain why.✨ Show Answer
Emojis above U+FFFF are encoded as a "surrogate pair" — two UTF-16 code units.
.lengthcounts code units, not code points.a7.jsconsole.log("😀".length); // 2 console.log([..."😀"].length); // 1 - Use
Intl.Segmenterto count graphemes in"ক্ষ মা".✨ Show Answer
a8.jsconst seg = new Intl.Segmenter("bn", { granularity: "grapheme" }); console.log([...seg.segment("ক্ষ মা")].length); - Build a tag function
safethat wraps each interpolated value in<b>...</b>.✨ Show Answer
a9.jsfunction safe(parts, ...vals) { return parts.reduce((a, p, i) => a + p + (vals[i] != null ? `<b>${vals[i]}</b>` : ""), ""); } console.log(safe`Hello, ${"Arif"}!`); - Capitalize only the first letter of each word.
✨ Show Answer
a10.jsconst title = s => s.split(" ") .map(w => w[0].toUpperCase() + w.slice(1)) .join(" "); console.log(title("hello bangla world")); - Test if a string is a palindrome (case-insensitive, alphanumeric only).
✨ Show Answer
a11.jsconst 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")); - Convert
"hello-world-today"to camelCase.✨ Show Answer
a12.jsconst camel = s => s.replace(/-([a-z])/g, (_, c) => c.toUpperCase()); console.log(camel("hello-world-today")); // "helloWorldToday" - Read a Bangla string and detect whether it contains the letter "ক".
✨ Show Answer
a13.jsconst str = "আমি বাংলাদেশের কথা বলি"; console.log(str.includes("ক")); - Why does
"5" + 3give "53" but"5" * 3gives 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"becomes5and the result is15.+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.
.length বিভ্রান্তিকর — সঠিক character count পেতে Intl.Segmenter।