javascript

examples

examples.js
/**
 * ========================================
 * 13.1 String Fundamentals - Examples
 * ========================================
 *
 * Comprehensive examples of JavaScript strings.
 */

/**
 * EXAMPLE 1: Creating Strings
 *
 * Different ways to create strings.
 */

// String literals
const single = 'Hello';
const double = 'World';
const template = `Hello World`;

console.log('Literals:', single, double, template);

// String constructor
const fromNumber = String(123); // '123'
const fromBoolean = String(true); // 'true'
const fromNull = String(null); // 'null'

console.log('Converted:', fromNumber, fromBoolean, fromNull);

// ⚠️ new String creates object, not primitive
const primitive = 'hello';
const object = new String('hello');

console.log('Primitive type:', typeof primitive); // 'string'
console.log('Object type:', typeof object); // 'object'
console.log('Equal value:', primitive == object); // true
console.log('Strict equal:', primitive === object); // false

/**
 * EXAMPLE 2: String Immutability
 *
 * Strings cannot be modified in place.
 */

const str = 'hello';

// This doesn't work
str[0] = 'H';
console.log('After assignment:', str); // Still 'hello'

// Must create new string
const capitalized = str[0].toUpperCase() + str.slice(1);
console.log('New string:', capitalized); // 'Hello'

// All methods return new strings
const original = 'Hello World';
const upper = original.toUpperCase();
console.log('Original:', original); // 'Hello World' (unchanged)
console.log('Upper:', upper); // 'HELLO WORLD'

/**
 * EXAMPLE 3: Accessing Characters
 *
 * Different ways to get characters.
 */

const text = 'JavaScript';

// Bracket notation
console.log('First:', text[0]); // 'J'
console.log('Fifth:', text[4]); // 'S'
console.log('Last (old):', text[text.length - 1]); // 't'
console.log('Out of bounds:', text[100]); // undefined

// .at() method (ES2022)
console.log('First (.at):', text.at(0)); // 'J'
console.log('Last (.at):', text.at(-1)); // 't'
console.log('Second last:', text.at(-2)); // 'p'

// charAt()
console.log('charAt(0):', text.charAt(0)); // 'J'
console.log('charAt(100):', text.charAt(100)); // '' (empty string)

// Character codes
console.log('charCodeAt(0):', text.charCodeAt(0)); // 74
console.log('codePointAt(0):', text.codePointAt(0)); // 74

/**
 * EXAMPLE 4: String Length
 */

const hello = 'Hello';
console.log('Length:', hello.length); // 5

// Empty string
console.log('Empty length:', ''.length); // 0

// Special characters count as one
console.log('Newline length:', 'Hi\n'.length); // 3
console.log('Tab length:', 'Hi\t'.length); // 3

// ⚠️ Emoji length (surrogate pairs)
console.log('Emoji length:', '😀'.length); // 2
console.log('Two emojis:', '😀🎉'.length); // 4

// Correct character count for emoji
console.log('Spread emoji:', [...'😀'].length); // 1
console.log('Spread two:', [...'😀🎉'].length); // 2

/**
 * EXAMPLE 5: Escape Sequences
 */

// Common escapes
console.log('New line:\nSecond line');
console.log('Tab:\tIndented');
console.log('Backslash: C:\\Users\\name');
console.log("Single quote: It's working");
console.log('Double quote: She said "Hi"');

// Unicode escapes
console.log('Heart:', '\u2764'); // ❤
console.log('Smiley:', '\u{1F600}'); // 😀
console.log('Pi:', '\u03C0'); // π

// Raw string (no escape processing in template)
console.log(String.raw`C:\Users\name\n`); // C:\Users\name\n

/**
 * EXAMPLE 6: Template Literals
 */

// Basic interpolation
const name = 'John';
const age = 30;
console.log(`Name: ${name}, Age: ${age}`);

// Expressions
const a = 10,
  b = 5;
console.log(`Sum: ${a + b}`); // 15
console.log(`Product: ${a * b}`); // 50
console.log(`Conditional: ${a > b ? 'a is bigger' : 'b is bigger'}`);

// Multi-line
const poem = `
    Roses are red,
    Violets are blue,
    JavaScript is cool,
    And so are you!
`;
console.log(poem);

// Nested templates
const items = ['Apple', 'Banana', 'Cherry'];
const list = `
<ul>
${items.map((item) => `  <li>${item}</li>`).join('\n')}
</ul>
`;
console.log(list);

// Calling functions
const double = (n) => n * 2;
console.log(`Doubled: ${double(5)}`); // 10

/**
 * EXAMPLE 7: Tagged Templates
 */

// Basic tag function
function highlight(strings, ...values) {
  let result = '';
  strings.forEach((str, i) => {
    result += str;
    if (values[i] !== undefined) {
      result += `**${values[i]}**`;
    }
  });
  return result;
}

const user = 'Alice';
const action = 'logged in';
console.log(highlight`User ${user} has ${action}`);
// 'User **Alice** has **logged in**'

// HTML escaping tag
function htmlSafe(strings, ...values) {
  const escape = (str) =>
    String(str)
      .replace(/&/g, '&amp;')
      .replace(/</g, '&lt;')
      .replace(/>/g, '&gt;')
      .replace(/"/g, '&quot;');

  return strings.reduce(
    (result, str, i) =>
      result + str + (values[i] !== undefined ? escape(values[i]) : ''),
    ''
  );
}

const userInput = '<script>alert("xss")</script>';
console.log(htmlSafe`User said: ${userInput}`);

/**
 * EXAMPLE 8: String Concatenation
 */

// + operator
const concat1 = 'Hello' + ' ' + 'World';
console.log('+ operator:', concat1);

// += operator
let message = 'Hello';
message += ' ';
message += 'World';
console.log('+= operator:', message);

// concat() method
const concat2 = 'Hello'.concat(' ', 'World', '!');
console.log('concat():', concat2);

// Template literals
const firstName = 'John';
const lastName = 'Doe';
const concat3 = `${firstName} ${lastName}`;
console.log('Template:', concat3);

// Array join (efficient for many strings)
const parts = ['Hello', 'World', 'How', 'Are', 'You'];
const concat4 = parts.join(' ');
console.log('join():', concat4);

/**
 * EXAMPLE 9: Case Conversion
 */

const mixed = 'Hello World';

console.log('Lower:', mixed.toLowerCase()); // 'hello world'
console.log('Upper:', mixed.toUpperCase()); // 'HELLO WORLD'

// Title case function
function toTitleCase(str) {
  return str.replace(/\b\w/g, (char) => char.toUpperCase());
}
console.log('Title:', toTitleCase('hello world')); // 'Hello World'

// Sentence case
function toSentenceCase(str) {
  return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();
}
console.log('Sentence:', toSentenceCase('hELLO wORLD')); // 'Hello world'

// Toggle case
function toggleCase(str) {
  return [...str]
    .map((c) => (c === c.toUpperCase() ? c.toLowerCase() : c.toUpperCase()))
    .join('');
}
console.log('Toggle:', toggleCase('Hello World')); // 'hELLO wORLD'

/**
 * EXAMPLE 10: Searching Strings
 */

const sentence = 'The quick brown fox jumps over the lazy dog';

// indexOf / lastIndexOf
console.log('indexOf "the":', sentence.indexOf('the')); // 31
console.log('indexOf "The":', sentence.indexOf('The')); // 0
console.log('lastIndexOf "the":', sentence.lastIndexOf('the')); // 31
console.log('indexOf "cat":', sentence.indexOf('cat')); // -1

// With start position
console.log('indexOf "o" from 15:', sentence.indexOf('o', 15)); // 17

// includes
console.log('includes "fox":', sentence.includes('fox')); // true
console.log('includes "cat":', sentence.includes('cat')); // false

// startsWith / endsWith
console.log('startsWith "The":', sentence.startsWith('The')); // true
console.log('endsWith "dog":', sentence.endsWith('dog')); // true
console.log('startsWith "quick" at 4:', sentence.startsWith('quick', 4)); // true

/**
 * EXAMPLE 11: Extracting Substrings
 */

const fullText = 'JavaScript Programming';

// slice(start, end) - most versatile
console.log('slice(0, 4):', fullText.slice(0, 4)); // 'Java'
console.log('slice(4):', fullText.slice(4)); // 'Script Programming'
console.log('slice(-11):', fullText.slice(-11)); // 'Programming'
console.log('slice(-11, -4):', fullText.slice(-11, -4)); // 'Program'
console.log('slice(4, -12):', fullText.slice(4, -12)); // 'Script'

// substring(start, end)
console.log('substring(0, 4):', fullText.substring(0, 4)); // 'Java'
console.log('substring(4, 0):', fullText.substring(4, 0)); // 'Java' (swaps)

// Negative values treated as 0 in substring
console.log('substring(-5):', fullText.substring(-5)); // Full string

/**
 * EXAMPLE 12: Trimming and Padding
 */

const padded = '   Hello World   ';

// Trim whitespace
console.log('trim:', `|${padded.trim()}|`); // '|Hello World|'
console.log('trimStart:', `|${padded.trimStart()}|`); // '|Hello World   |'
console.log('trimEnd:', `|${padded.trimEnd()}|`); // '|   Hello World|'

// Padding
console.log('padStart:', '42'.padStart(5, '0')); // '00042'
console.log('padEnd:', '42'.padEnd(5, '-')); // '42---'
console.log('padStart spaces:', 'Hi'.padStart(10)); // '        Hi'

// Practical: format numbers
const formatNumber = (num) => String(num).padStart(3, '0');
console.log('Format 5:', formatNumber(5)); // '005'
console.log('Format 42:', formatNumber(42)); // '042'

// Practical: align columns
const data = [
  { name: 'Apple', price: 1.5 },
  { name: 'Banana', price: 0.75 },
  { name: 'Cherry', price: 2.0 },
];
data.forEach((item) => {
  console.log(item.name.padEnd(10) + '$' + item.price.toFixed(2).padStart(5));
});

/**
 * EXAMPLE 13: Repeating Strings
 */

console.log('repeat:', 'abc'.repeat(3)); // 'abcabcabc'
console.log('separator:', '-'.repeat(20)); // '--------------------'

// Indentation
function indent(text, level) {
  const spaces = '  '.repeat(level);
  return text
    .split('\n')
    .map((line) => spaces + line)
    .join('\n');
}

const code = `function hello() {
console.log("Hi");
}`;
console.log(indent(code, 2));

/**
 * EXAMPLE 14: Splitting Strings
 */

// Split by character
console.log('split comma:', 'a,b,c'.split(',')); // ['a', 'b', 'c']
console.log('split space:', 'hello world'.split(' ')); // ['hello', 'world']

// Split into characters
console.log('split chars:', 'hello'.split('')); // ['h', 'e', 'l', 'l', 'o']

// Limit results
console.log('split limit:', 'a,b,c,d'.split(',', 2)); // ['a', 'b']

// Split by regex
console.log('split regex:', 'a1b2c3'.split(/\d/)); // ['a', 'b', 'c', '']

// Keep delimiters
console.log('keep delim:', 'a1b2c3'.split(/(\d)/)); // ['a', '1', 'b', '2', 'c', '3', '']

// Split lines
const multiline = 'Line 1\nLine 2\nLine 3';
console.log('lines:', multiline.split('\n'));

/**
 * EXAMPLE 15: Replacing Content
 */

const original2 = 'Hello World, Hello Universe';

// replace - first only
console.log('replace first:', original2.replace('Hello', 'Hi'));
// 'Hi World, Hello Universe'

// replaceAll - all occurrences
console.log('replaceAll:', original2.replaceAll('Hello', 'Hi'));
// 'Hi World, Hi Universe'

// Case-insensitive with regex
console.log('regex replace:', 'HELLO hello HeLLo'.replace(/hello/gi, 'hi'));
// 'hi hi hi'

// Replacement with capture groups
const name2 = 'John Doe';
console.log('swap:', name2.replace(/(\w+) (\w+)/, '$2, $1'));
// 'Doe, John'

// Replacement function
const prices = 'Item costs $10 and $20';
const doubled2 = prices.replace(
  /\$(\d+)/g,
  (match, num) => '$' + parseInt(num) * 2
);
console.log('doubled:', doubled2); // 'Item costs $20 and $40'

/**
 * EXAMPLE 16: String Comparison
 */

// Simple comparison
console.log('abc === abc:', 'abc' === 'abc'); // true
console.log('abc === ABC:', 'abc' === 'ABC'); // false

// Lexicographic comparison
console.log('a < b:', 'a' < 'b'); // true
console.log('B < a:', 'B' < 'a'); // true (uppercase < lowercase in ASCII)
console.log('10 < 9:', '10' < '9'); // true (string comparison!)

// localeCompare for proper sorting
const words = ['banana', 'Apple', 'cherry'];
console.log('default sort:', [...words].sort());
// ['Apple', 'banana', 'cherry'] - uppercase first

console.log(
  'locale sort:',
  [...words].sort((a, b) =>
    a.localeCompare(b, undefined, { sensitivity: 'base' })
  )
);
// ['Apple', 'banana', 'cherry'] - case-insensitive

// Case-insensitive equality
function equalsIgnoreCase(a, b) {
  return a.toLowerCase() === b.toLowerCase();
}
console.log('equalsIgnoreCase:', equalsIgnoreCase('Hello', 'HELLO'));

/**
 * EXAMPLE 17: Unicode and Emoji
 */

// Emoji are multiple code units
const emoji = '😀';
console.log('emoji length:', emoji.length); // 2
console.log('emoji[0]:', emoji[0]); // '\uD83D' (garbage)

// Correct iteration
console.log('spread emoji:', [...emoji]); // ['😀']

// for...of works correctly
console.log('iterate:');
for (const char of '😀🎉👍') {
  console.log(' ', char);
}

// String.fromCodePoint
console.log('fromCodePoint:', String.fromCodePoint(128512)); // '😀'

// Get code point
console.log('codePointAt:', '😀'.codePointAt(0)); // 128512

// Combining characters
const cafe1 = 'café'; // 4 characters
const cafe2 = 'cafe\u0301'; // 5 code units, same appearance
console.log('café compare:', cafe1 === cafe2); // false!
console.log('normalized:', cafe1.normalize() === cafe2.normalize()); // true

/**
 * EXAMPLE 18: Common String Patterns
 */

// Check if string is empty or whitespace
const isEmpty = (str) => !str || str.trim().length === 0;
console.log('isEmpty "":', isEmpty('')); // true
console.log('isEmpty "   ":', isEmpty('   ')); // true
console.log('isEmpty "hi":', isEmpty('hi')); // false

// Truncate with ellipsis
function truncate(str, maxLength) {
  if (str.length <= maxLength) return str;
  return str.slice(0, maxLength - 3) + '...';
}
console.log('truncate:', truncate('Hello World', 8)); // 'Hello...'

// Capitalize first letter
const capitalize = (str) => str.charAt(0).toUpperCase() + str.slice(1);
console.log('capitalize:', capitalize('hello')); // 'Hello'

// Count occurrences
function countOccurrences(str, search) {
  return str.split(search).length - 1;
}
console.log('count "l":', countOccurrences('hello world', 'l')); // 3

// Reverse string
const reverse = (str) => [...str].reverse().join('');
console.log('reverse:', reverse('hello')); // 'olleh'
console.log('reverse emoji:', reverse('😀🎉')); // '🎉😀'

// Check palindrome
function isPalindrome(str) {
  const clean = str.toLowerCase().replace(/[^a-z0-9]/g, '');
  return clean === [...clean].reverse().join('');
}
console.log('palindrome "racecar":', isPalindrome('racecar')); // true
console.log(
  'palindrome "A man a plan":',
  isPalindrome('A man, a plan, a canal: Panama')
); // true

console.log('\nString fundamentals examples completed!');
Examples - JavaScript Tutorial | DeepML