Lesson 03-Data Structures – Strings

String Basics

String Encoding (UTF-8, Unicode)

In JavaScript, strings are sequences of characters based on Unicode encoding. Understanding Unicode and UTF-8 encoding is crucial for correctly handling multilingual text.

Unicode Introduction

Unicode is a globally unified character encoding standard designed to assign a unique number (called a code point) to every character in all writing systems worldwide. The main features of Unicode include:

  1. Code Point: The unique identifier for each character in Unicode, usually represented as “U+” followed by a hexadecimal number. For example:
    • ‘A’ has code point U+0041
    • ‘汉’ has code point U+6C49
    • ‘😊’ has code point U+1F60A
  2. Planes: Unicode divides code points into 17 planes, each containing 65,536 code points:
    • Basic Multilingual Plane (BMP): U+0000 to U+FFFF (contains most common characters)
    • Supplementary Planes: U+10000 to U+10FFFF (contains emojis, ancient scripts, etc.)

UTF-8 Encoding

UTF-8 is a variable-length character encoding for Unicode, capable of representing any Unicode character using 1 to 4 bytes. The main features of UTF-8 include:

  1. ASCII Compatibility: ASCII characters (U+0000 to U+007F) are represented using a single byte in UTF-8, identical to ASCII encoding.
  2. Variable Length:
    • 1 byte: U+0000 to U+007F
    • 2 bytes: U+0080 to U+07FF
    • 3 bytes: U+0800 to U+FFFF
    • 4 bytes: U+10000 to U+10FFFF
  3. Encoding Rules:
    • For multi-byte characters, the first byte starts with a specific number of 1s followed by a 0, indicating the number of bytes for that character. Subsequent bytes start with 10.
    • For example:
      • ‘A’ (U+0041) → 01000001 (single byte)
      • ‘汉’ (U+6C49) → 11100110 10110001 10010010 (three bytes)

Strings and Encoding in JavaScript

In JavaScript, strings consist of a sequence of code units encoded in UTF-16:

  1. UTF-16 Introduction:
    • Uses 16-bit (2-byte) code units to represent characters
    • Basic Multilingual Plane (BMP) characters use a single code unit (U+0000 to U+FFFF)
    • Supplementary plane characters use surrogate pairs, i.e., two 16-bit code units (total 4 bytes)
  2. Surrogate Pair Example:
    • ‘😊’ (U+1F60A) in UTF-16 is represented as surrogate pair: 0xD83D 0xDE0A
    • In JavaScript, these can be handled using codePointAt() and fromCodePoint() methods
  3. JavaScript String Methods:
    • The length property returns the number of code units, not the number of characters
    • For strings containing surrogate pairs, length may be greater than the actual number of visible characters
const emoji = '😊';
console.log(emoji.length); // 2 (because it's a surrogate pair)
console.log(emoji.codePointAt(0)); // 128522 (U+1F60A)
console.log(String.fromCodePoint(128522)); // '😊'

Handling Multi-Byte Characters

When needing to correctly handle multi-byte characters, the following methods can be used:

  1. ES6 Added Methods:
    • codePointAt(index): Returns the Unicode code point of the character at the specified position (supports surrogate pairs)
    • fromCodePoint(...codePoints): Creates a string from code points
    • String.prototype.normalize(): Normalizes Unicode strings
  2. Iterating Strings:
    • Using for...of loop can correctly iterate over all characters (including surrogate pairs)
const str = 'Hello 😊 World';
for (const char of str) {
  console.log(char); // Correctly outputs each character, including emojis
}

Immutability of JavaScript Strings

Strings in JavaScript are immutable, meaning once created, their content cannot be modified. Any operation that appears to modify a string actually creates a new string.

Manifestation of Immutability

  1. Modification Operations Return New Strings:
let str = 'hello';
const newStr = str.toUpperCase(); // Creates a new string
console.log(str); // 'hello' (original string unchanged)
console.log(newStr); // 'HELLO'
  1. Performance Considerations:
  • Frequent string modifications may lead to performance issues (since each modification creates a new string)
  • For extensive string operations, consider using arrays or the StringBuilder pattern

    Implementation Principle of Immutability

    JavaScript engines typically implement string immutability through the following ways:

    1. Memory Allocation: Strings are stored in memory as contiguous sequences of characters
    2. Modification Operations: When “modification” is needed, the engine allocates new memory and copies the original content
    3. Optimization Techniques: Some engines may use string interning to reuse identical strings

    Workspace Example

    // Performance issues with string concatenation
    let result = '';
    for (let i = 0; i < 100000; i++) {
      result += i.toString(); // Creates a new string each loop
    }
    
    // Better way: Use array and join
    const parts = [];
    for (let i = 0; i < 100000; i++) {
      parts.push(i.toString());
    }
    const betterResult = parts.join('');
    

    Conversion Between Character Arrays and Strings

    JavaScript provides multiple methods to convert between character arrays and strings.

    String to Character Array

    1. split() Method:
    const str = 'hello';
    const arr = str.split(''); // ['h', 'e', 'l', 'l', 'o']
    
    1. Spread Operator (ES6):
    const arr = [...'hello']; // ['h', 'e', 'l', 'l', 'o']
    
    1. Array.from():
    const arr = Array.from('hello'); // ['h', 'e', 'l', 'l', 'o']
    

    Character Array to String

    1. join() Method:
    const arr = ['h', 'e', 'l', 'l', 'o'];
    const str = arr.join(''); // 'hello'
    
    1. String() Constructor:
    const str = String(['h', 'e', 'l', 'l', 'o']); // 'h,e,l,l,o' (not recommended)
    // Better to use join()
    
    1. Spread Operator with Template Strings (ES6):
    const arr = ['h', 'e', 'l', 'l', 'o'];
    const str = `${arr}`; // 'h,e,l,l,o' (not recommended)
    // Better way:
    const betterStr = [...arr].join(''); // 'hello'
    

    Advanced Conversion Examples

    1. Handling Unicode Characters:
    const emojiStr = '😊🌍';
    const emojiArr = [...emojiStr]; // ['😊', '🌍']
    console.log(emojiArr.length); // 2
    
    const backToStr = emojiArr.join(''); // '😊🌍'
    
    1. Filtering and Transforming Characters:
    const str = 'Hello World 123';
    const filtered = [...str].filter(c => /[a-zA-Z]/.test(c)).join('');
    // 'HelloWorld'
    
    const upper = [...str].map(c => c.toUpperCase()).join('');
    // 'HELLO WORLD 123'
    
    1. Handling Surrogate Pairs:
    const strWithEmoji = 'A😊B';
    const arr = [...strWithEmoji]; // ['A', '😊', 'B']
    
    // Correctly get character code point
    console.log(arr[1].codePointAt(0)); // 128522 (U+1F60A)
    
    1. Performance Considerations:
    // Handling large strings
    const bigStr = 'a'.repeat(1000000);
    
    // Not recommended: Creates new array each loop
    let result = '';
    for (let i = 0; i < bigStr.length; i++) {
      result += bigStr[i]; // Implicitly creates new string
    }
    
    // Recommended: Use array and join
    const arr = [];
    for (let i = 0; i < bigStr.length; i++) {
      arr.push(bigStr[i]);
    }
    const betterResult = arr.join('');
    

    Understanding the conversion between character arrays and strings is crucial for efficiently handling text data, especially when individual character operations or Unicode characters are involved.

    String Operations

    Concatenation and Splitting (concat, split)

    String concatenation and splitting are the most basic operations in text processing, and JavaScript provides multiple methods to achieve these functions.

    Concatenating Strings

    1. concat() Method:
    const str1 = 'Hello';
    const str2 = 'World';
    const result = str1.concat(' ', str2); // 'Hello World'
    
    • Can accept multiple parameters for concatenation
    • Does not modify the original string, returns a new string
    • For large concatenation operations, performance is not as good as array join()
    1. Plus Operator (+):
    const result = 'Hello' + ' ' + 'World'; // 'Hello World'
    
    • Simple and intuitive
    • May cause performance issues when used in loops (creates a new string each concatenation)
    1. Template Strings (ES6):
    const name = 'Alice';
    const greeting = `Hello, ${name}!`; // 'Hello, Alice!'
    
    • Supports embedded expressions
    • More readable, especially for multiline strings
    1. Array join() Method (suitable for large concatenations):
    const parts = ['Hello', 'World'];
    const result = parts.join(' '); // 'Hello World'
    
    • Better performance than multiple uses of + or concat()
    • Particularly suitable for building strings in loops

    Splitting Strings

    1. split() Method:
    const str = 'apple,banana,orange';
    const arr = str.split(','); // ['apple', 'banana', 'orange']
    
    • Can specify the delimiter
    • If no delimiter is specified, returns an array containing the original string
    • Can limit the length of the returned array
    const str2 = 'apple,banana,orange';
    const arr2 = str2.split(',', 2); // ['apple', 'banana']
    
    1. Regular Expression as Delimiter:
    const str = 'apple  banana   orange';
    const arr = str.split(/\s+/); // ['apple', 'banana', 'orange']
    
    1. Handling Unicode Characters:
    const str = '😊🌍🚀';
    const arr = [...str]; // Simpler to use spread operator
    // Or
    const arr2 = str.split(/(?=[\uD800-\uDBFF][\uDC00-\uDFFF])|(?<=[\uD800-\uDBFF])(?=[\uDC00-\uDFFF])|./);
    // Note: split directly may not handle surrogate pairs correctly
    
    • More recommended to use spread operator or Array.from()
    const arr = [...'😊🌍🚀']; // ['😊', '🌍', '🚀']
    

    Practical Application Examples

    1. CSV Parsing:
    function parseCSV(text) {
      return text.split('\n').map(line => line.split(','));
    }
    
    const csv = 'name,age\nAlice,30\nBob,25';
    const data = parseCSV(csv);
    // [['name', 'age'], ['Alice', '30'], ['Bob', '25']]
    
    1. Path Processing:
    function getPathParts(path) {
      return path.split('/').filter(part => part.length > 0);
    }
    
    const path = '/usr/local/bin/node';
    const parts = getPathParts(path); // ['usr', 'local', 'bin', 'node']
    
    1. Word Counting:
    function countWords(text) {
      const words = text.trim().split(/\s+/);
      return words.filter(word => word.length > 0).length;
    }
    
    const text = '  Hello   world  ';
    console.log(countWords(text)); // 2
    

    Searching and Replacing (indexOf, replace)

    Searching and replacing are another basic operation in string processing, and JavaScript provides multiple methods to achieve these functions.

    Searching for Substrings

    1. indexOf() Method:
    const str = 'Hello World';
    const index = str.indexOf('World'); // 6
    
    • Returns the index of the first occurrence of the substring
    • If not found, returns -1
    • Can specify the starting search position
    const index2 = str.indexOf('o', 5); // Starts searching for 'o' from index 5, returns 7
    
    1. lastIndexOf() Method:
    const str = 'Hello World Hello';
    const index = str.lastIndexOf('Hello'); // 12
    
    • Returns the index of the last occurrence of the substring
    • Can specify the starting search position
    1. includes() Method (ES6):
    const str = 'Hello World';
    const hasHello = str.includes('Hello'); // true
    
    • Returns a boolean indicating whether the substring is contained
    • More intuitive and readable
    1. startsWith() and endsWith() Methods (ES6):
    const str = 'Hello World';
    const startsWithHello = str.startsWith('Hello'); // true
    const endsWithWorld = str.endsWith('World'); // true
    

    Replacing Substrings

    1. replace() Method:
    const str = 'Hello World';
    const newStr = str.replace('World', 'JavaScript'); // 'Hello JavaScript'
    
    • By default, replaces only the first match
    • Can use regular expressions for global replacement
    const newStr2 = str.replace(/World/g, 'JavaScript'); // 'Hello JavaScript'
    
    1. Regular Expression Replacement:
    const str = 'The quick brown fox jumps over the lazy dog';
    const newStr = str.replace(/\b\w{3}\b/g, '*'.repeat(3)); // 'The *** brown *** jumps over the *** dog'
    
    • \b indicates word boundary
    • \w{3} matches 3 alphanumeric characters
    1. Replacement Function:
    const str = 'The price is $100 and $200';
    const newStr = str.replace(/\$\d+/g, match => {
      return '$' + parseInt(match.slice(1)) * 1.1; // Add 10% tax
    });
    // 'The price is $110 and $220'
    
    1. Case Conversion:
    const str = 'Hello World';
    const upper = str.toUpperCase(); // 'HELLO WORLD'
    const lower = str.toLowerCase(); // 'hello world'
    

    Practical Application Examples

    1. Sensitive Word Filtering:
    function filterSensitiveWords(text, badWords) {
      let result = text;
      badWords.forEach(word => {
    	const regex = new RegExp(word, 'gi');
    	result = result.replace(regex, '*'.repeat(word.length));
      });
      return result;
    }
    
    const text = 'This is a bad word example with badword';
    const badWords = ['bad', 'badword'];
    console.log(filterSensitiveWords(text, badWords));
    // 'This is a *** word example with *********'
    
    1. URL Parameter Parsing:
    function getQueryParams(url) {
      const query = url.split('?')[1];
      if (!query) return {};
      
      return query.split('&').reduce((params, pair) => {
    	const [key, value] = pair.split('=');
    	params[key] = decodeURIComponent(value || '');
    	return params;
      }, {});
    }
    
    const url = 'https://example.com/page?name=John&age=30';
    console.log(getQueryParams(url)); // { name: 'John', age: '30' }
    
    1. String Template Replacement:
    function templateReplace(template, data) {
      return template.replace(/\$\{(\w+)\}/g, (match, key) => {
    	return data[key] !== undefined ? data[key] : match;
      });
    }
    
    const template = 'Hello, ${name}! Today is ${day}.';
    const data = { name: 'Alice', day: 'Monday' };
    console.log(templateReplace(template, data)); // 'Hello, Alice! Today is Monday.'
    

    Regular Expression Basics

    Regular expressions are powerful tools for text processing, and JavaScript provides full support for regular expressions.

    Creating Regular Expressions

    1. Literal Syntax:
    const regex = /pattern/flags;
    
    1. Constructor:
    const reg...(truncated 1295 characters)...ml.match(contentRegex)[1]); // 'Hello'
    
    1. Password Strength Validation:
    const passwordRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/;
    console.log(passwordRegex.test('Password1!')); // true
    

    Advanced Features of Regular Expressions

    1. Lookahead and Lookbehind:
    • Positive lookahead: (?=pattern)
    • Negative lookahead: (?!pattern)
    • Positive lookbehind: (?<=pattern)
    • Negative lookbehind: (?<!pattern)
    // Match letters followed by digits
    const regex = /[a-zA-Z](?=\d)/;
    console.log(regex.test('a1')); // true
    console.log(regex.test('a')); // false
    
    1. Named Capture Groups (ES2018):
    const dateRegex = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/;
    const match = '2023-05-15'.match(dateRegex);
    console.log(match.groups.year); // '2023'
    console.log(match.groups.month); // '05'
    
    1. Sticky Matching (sticky flag y):
    const regex = /world/y;
    console.log(regex.test('Hello world')); // true
    regex.lastIndex = 0; // Must reset manually
    console.log(regex.test('world hello')); // true
    

    Performance Considerations

    1. Avoid Greedy Matching:
    // Greedy matching matches as much as possible
    const greedy = 'abc123def456'.match(/\d+/)[0]; // '123def456'
    
    // Non-greedy (lazy) matching matches as little as possible
    const lazy = 'abc123def456'.match(/\d+?/)[0]; // '1'
    // Correct non-greedy should be: /\d+?(?=\D|$)/ or use a more precise pattern
    
    1. Precompile Regular Expressions:
    // Precompile outside the loop
    const regex = /\d+/g;
    for (let i = 0; i < 1000; i++) {
      'abc123'.match(regex);
    }
    
    1. Avoid Complex Regular Expressions:
    • For very complex patterns, consider breaking them into multiple simple steps
    • Complex regular expressions may be hard to maintain and perform poorly

    Understanding the basics of regular expressions is crucial for efficiently handling strings and text data, especially in scenarios like data validation, search, and extraction.

    String Applications

    Text Processing and Parsing

    Text processing is a common task in programming, and JavaScript provides rich tools to handle various text operations.

    Basic Text Processing

    1. Removing Whitespace Characters:
    const str = '  Hello World  ';
    const trimmed = str.trim(); // 'Hello World'
    const trimmedStart = str.trimStart(); // 'Hello World  '
    const trimmedEnd = str.trimEnd(); // '  Hello World'
    
    1. Repeating Strings:
    const repeated = 'abc'.repeat(3); // 'abcabcabc'
    
    1. Padding Strings:
    const padded = '5'.padStart(3, '0'); // '005'
    const paddedEnd = '5'.padEnd(3, '0'); // '500'
    

    Advanced Text Parsing

    1. CSV Parsing:
    function parseCSV(text, delimiter = ',') {
      return text.split('\n').map(line => {
    	return line.split(new RegExp(`(?<!\\\\)${delimiter}`)).map(field => {
    	  return field.replace(/\$.)/g, '$1');
    	});
      });
    }
    
    const csv = 'name,age\\,years\nJohn,30\\,years\nJane,25';
    console.log(parseCSV(csv));
    // [ [ 'name', 'age,years' ], [ 'John', '30,years' ], [ 'Jane', '25' ] ]
    
    1. JSON String Processing:
    function safeJsonParse(jsonString, defaultValue = null) {
      try {
    	return JSON.parse(jsonString);
      } catch (e) {
    	return defaultValue;
      }
    }
    
    console.log(safeJsonParse('{ "name": "John" }')); // { name: 'John' }
    console.log(safeJsonParse('invalid', {})); // {}
    
    1. Log Formatting:
    function formatLog(timestamp, level, message) {
      return `[${timestamp.toISOString()}] [${level.toUpperCase()}] ${message}`;
    }
    
    const log = formatLog(new Date(), 'info', 'Application started');
    // '[2023-05-15T12:00:00.000Z] [INFO] Application started'
    

    Practical Application Examples

    1. Markdown Conversion:
    function simpleMarkdownToHtml(markdown) {
      return markdown
    	.replace(/^###### (.*)$/gm, '<h6>$1</h6>')
    	.replace(/^##### (.*)$/gm, '<h5>$1</h5>')
    	.replace(/^#### (.*)$/gm, '<h4>$1</h4>')
    	.replace(/^### (.*)$/gm, '<h3>$1</h3>')
    	.replace(/^## (.*)$/gm, '<h2>$1</h2>')
    	.replace(/^# (.*)$/gm, '<h1>$1</h1>')
    	.replace(/\*\*(.*)\*\*/g, '<strong>$1</strong>')
    	.replace(/\*(.*)\*/g, '<em>$1</em>')
    	.replace(/!$$([^$$]*)\]\(([^$]*)\)/g, '<img alt="$1" src="$2">')
    	.replace(/$$([^$$]*)\]$([^$]*)\)/g, '<a href="$2">$1</a>')
    	.replace(/\n/g, '<br>');
    }
    
    const md = '# Hello\n**World**\n[Link](https://example.com)';
    console.log(simpleMarkdownToHtml(md));
    // '<h1>Hello</h1><br><strong>World</strong><br><a href="https://example.com">Link</a><br>'
    
    1. String Template Engine:
    function templateEngine(template, data) {
      return template.replace(/\$\{([^}]+)\}/g, (match, key) => {
    	const keys = key.split('.');
    	let value = data;
    	for (const k of keys) {
    	  if (value === undefined || value === null) break;
    	  value = value[k];
    	}
    	return value !== undefined && value !== null ? value : match;
      });
    }
    
    const tpl = 'Hello, ${user.name}! Your balance is ${account.balance}.';
    const data = { user: { name: 'John' }, account: { balance: 100 } };
    console.log(templateEngine(tpl, data));
    // 'Hello, John! Your balance is 100.'
    
    1. Basic Natural Language Processing:
    function countWords(text) {
      return text.trim().split(/\s+/).filter(word => word.length > 0).length;
    }
    
    function countSentences(text) {
      return text.split(/[.!?]+/).filter(sentence => sentence.trim().length > 0).length;
    }
    
    const text = 'Hello world! How are you? I am fine.';
    console.log(countWords(text)); // 7
    console.log(countSentences(text)); // 3
    

    URL Parameter Processing

    URL parameter processing is a common task in web development, and JavaScript provides multiple methods to parse and build URL parameters.

    Parsing URL Parameters

    1. Basic Parsing:
    function getQueryParams(url) {
      const query = url.split('?')[1];
      if (!query) return {};
      
      return query.split('&').reduce((params, pair) => {
    	const [key, value] = pair.split('=');
    	params[decodeURIComponent(key)] = decodeURIComponent(value || '');
    	return params;
      }, {});
    }
    
    const url = 'https://example.com/page?name=John&age=30';
    console.log(getQueryParams(url)); // { name: 'John', age: '30' }
    
    1. Handling Array Parameters:
    function getQueryParamsAdvanced(url) {
      const query = url.split('?')[1];
      if (!query) return {};
      
      return query.split('&').reduce((params, pair) => {
    	const [key, value] = pair.split('=');
    	const decodedKey = decodeURIComponent(key);
    	const decodedValue = decodeURIComponent(value || '');
    	
    	if (decodedKey.endsWith('[]')) {
    	  const arrayKey = decodedKey.slice(0, -2);
    	  if (!params[arrayKey]) params[arrayKey] = [];
    	  params[arrayKey].push(decodedValue);
    	} else {
    	  params[decodedKey] = decodedValue;
    	}
    	
    	return params;
      }, {});
    }
    
    const url = 'https://example.com/page?name=John&colors[]=red&colors[]=blue';
    console.log(getQueryParamsAdvanced(url));
    // { name: 'John', colors: ['red', 'blue'] }
    

    Building URL Parameters

    1. Basic Building:
    function buildQueryParams(params) {
      return Object.entries(params)
    	.map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
    	.join('&');
    }
    
    const params = { name: 'John', age: 30 };
    console.log(buildQueryParams(params)); // 'name=John&age=30'
    
    1. Handling Complex Parameters:
    function buildQueryParamsAdvanced(params) {
      return Object.entries(params).map(([key, value]) => {
    	if (Array.isArray(value)) {
    	  return value.map(v => `${encodeURIComponent(key)}[]=${encodeURIComponent(v)}`).join('&');
    	}
    	return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
      }).join('&');
    }
    
    const params = { name: 'John', colors: ['red', 'blue'] };
    console.log(buildQueryParamsAdvanced(params)); // 'name=John&colors[]=red&colors[]=blue'
    

    Practical Application Examples

    1. Pagination Parameter Processing:
    function updatePaginationUrl(url, page, pageSize) {
      const params = getQueryParams(url);
      params.page = page;
      if (pageSize !== undefined) params.pageSize = pageSize;
      const queryString = buildQueryParams(params);
      const base = url.split('?')[0];
      return queryString ? `${base}?${queryString}` : base;
    }
    
    const url = 'https://example.com/items?page=1';
    console.log(updatePaginationUrl(url, 2, 10));
    // 'https://example.com/items?page=2&pageSize=10'
    
    1. Hash Parameter Processing:
    function getHashParams() {
      const hash = window.location.hash.substring(1);
      if (!hash) return {};
      
      return hash.split('&').reduce((params, pair) => {
    	const [key, value] = pair.split('=');
    	params[decodeURIComponent(key)] = decodeURIComponent(value || '');
    	return params;
      }, {});
    }
    
    // Assume current URL is https://example.com/#name=John&age=30
    console.log(getHashParams()); // { name: 'John', age: '30' }
    
    1. URL Parameter Observer:
    function observeUrlParams(callback) {
      const updateParams = () => {
    	const params = getQueryParams(window.location.href);
    	callback(params);
      };
      
      window.addEventListener('popstate', updateParams);
      updateParams();
      
      return () => {
    	window.removeEventListener('popstate', updateParams);
      };
    }
    
    // Usage example
    const unobserve = observeUrlParams(params => {
      console.log('URL params changed:', params);
    });
    
    // Call unobserve() when stopping observation
    

    Input Validation and Formatting

    Input validation and formatting are key aspects in ensuring application robustness and user experience.

    Basic Validation

    1. Required Field Validation:
    function isRequired(value) {
      return value !== null && value !== undefined && value !== '';
    }
    
    console.log(isRequired('')); // false
    console.log(isRequired(null)); // false
    console.log(isRequired(undefined)); // false
    console.log(isRequired('text')); // true
    
    1. Type Validation:
    function isString(value) {
      return typeof value === 'string' || value instanceof String;
    }
    
    console.log(isString('text')); // true
    console.log(isString(123)); // false
    

    Complex Validation

    1. Email Validation:
    function isValidEmail(email) {
      const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      return regex.test(email);
    }
    
    console.log(isValidEmail('test@example.com')); // true
    console.log(isValidEmail('invalid-email')); // false
    
    1. Password Strength Validation:
    function isStrongPassword(password) {
      return password.length >= 8 && 
    		 /[A-Z]/.test(password) && 
    		 /[a-z]/.test(password) && 
    		 /\d/.test(password) && 
    		 /[@$!%*?&]/.test(password);
    }
    
    console.log(isStrongPassword('Password1!')); // true
    console.log(isStrongPassword('weak')); // false
    

    Formatting

    1. Date Formatting:
    function formatDate(date, format = 'YYYY-MM-DD') {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      
      return format
    	.replace('YYYY', year)
    	.replace('MM', month)
    	.replace('DD', day)
    	.replace('HH', hours)
    	.replace('mm', minutes)
    	.replace('ss', seconds);
    }
    
    const now = new Date();
    console.log(formatDate(now)); // '2023-05-15'
    console.log(formatDate(now, 'YYYY/MM/DD HH:mm:ss')); // '2023/05/15 14:30:45'
    
    Share your love