Home/Learn/JavaScript & TypeScript/Strings — Templates, Methods and Unicode

Strings — Templates, Methods and Unicode

Beginner
Working with Data

Template literals handle interpolation and multi-line text; the method set covers most parsing needs. The one trap is that .length counts UTF-16 code units, not characters.

Overview

Strings are immutable — every method returns a new string rather than modifying in place. Template literals replaced concatenation for anything with a variable in it, and support multi-line text and tagged templates. The subtlety worth knowing early is Unicode: JavaScript strings are sequences of UTF-16 code units, so emoji and many Indic characters occupy two units, and .length reports something other than what a user would count.

Template Literals

Backticks give interpolation, multi-line strings and expression embedding.

Interpolation, multi-line, tagged
const name = 'Asha'
const total = 4500

`Hello ${name}, your total is ₹${(total / 100).toFixed(2)}`

// Multi-line, preserved exactly
const query = `
  SELECT id, title
  FROM problems
  WHERE difficulty = '${level}'
`

// Any expression, including calls and ternaries
`You have ${count} item${count === 1 ? '' : 's'}`

// Tagged templates — the function receives parts and values
function html(strings, ...values) { ... }
html`<p>${userInput}</p>`      // used for escaping, styled-components, SQL builders

The Methods You Actually Need

Grouped by intent rather than alphabetically.

Clean, test, slice, split, replace
const s = '  Hello World  '

// Cleaning
s.trim()                    // 'Hello World'
s.trimStart()  s.trimEnd()

// Testing
s.includes('World')         // true
s.startsWith('  He')        // true
s.endsWith('  ')            // true

// Slicing
s.slice(2, 7)               // 'Hello'  — negative indices allowed
s.slice(-3)                 // last 3 characters

// Splitting and joining
'a,b,c'.split(',')          // ['a','b','c']
['a','b'].join('-')         // 'a-b'

// Replacing — replaceAll avoids the regex-with-/g dance
'a-b-c'.replaceAll('-', '_')          // 'a_b_c'
'a-b-c'.replace(/-/g, '_')            // same, older

// Padding, useful for display
'7'.padStart(2, '0')        // '07'

Unicode and .length

The trap: .length counts UTF-16 code units. Characters outside the basic plane — emoji, some scripts — count as two.

Why .length lies, and Intl
'hello'.length        // 5
'🎉'.length           // 2  — one character, two code units
'नमस्ते'.length        // 6  — includes combining marks

// Counting actual characters:
[...'🎉🎉'].length              // 2 — spread iterates code points
Array.from('🎉🎉').length       // 2

// Intl.Segmenter for true user-perceived characters:
const seg = new Intl.Segmenter('en', { granularity: 'grapheme' })
[...seg.segment('👨‍👩‍👧')].length     // 1

// Locale-aware comparison and formatting:
['b', 'a', 'ä'].sort(new Intl.Collator('de').compare)
new Intl.NumberFormat('en-IN', {
  style: 'currency', currency: 'INR',
}).format(4500)         // '₹4,500.00'

Key Points to Remember

  • 1Strings are immutable — every method returns a new string
  • 2Template literals handle interpolation, multi-line text and expressions; tagged templates power escaping libraries
  • 3replaceAll() replaces every occurrence without needing a global regex
  • 4.length counts UTF-16 code units, so emoji count as 2 — spread or Intl.Segmenter for real character counts
  • 5Intl.NumberFormat with en-IN gives correct rupee formatting including the Indian digit grouping

Interview Questions

Sign in to ask Aria
1

Why does "🎉".length return 2?

Medium
2

What is a tagged template literal and what is it used for?

Medium
3

How would you format a number as Indian rupees with correct grouping?

Easy

Ask Aria about Strings — Templates, Methods and Unicode

Your personal AI tutor — ask anything about this concept

Revision Status

Personal Notes

Sign in to save personal notes for this topic.

Discussion

Sign in to join the discussion.

Loading discussion…