Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Manipulating DOM Nodes and Using Regular Expressions in JavaScript

Tech 2

Node Operations

Creating Nodes

The document.createElement() method creates a new element node.

let newDiv = document.createElement('div');

Inserting Nodes

  • appendChild(): Adds a node to the end of another node's list of children.
parentContainer.appendChild(newDiv);
  • insertBefore(): Inserts a node before a specfiied reference node within a parent's child list.
parentContainer.insertBefore(newDiv, existingNode);

Removing Nodes

The removeChild() method removes a node from the DOM.

parentContainer.removeChild(nodeToRemove);

Replacing Nodes

The replaceChild() method replaces one child node with another.

parentContainer.replaceChild(updatedNode, oldNode);

Traversign Nodes via Relationships

Parent-Child Relationships

  • Parenet Element: An element that contains other elements.
  • Child Element: An element directly contained within another.

JavaScript provides these properties for accessing these relationships:

  • parentNode: Gets the parent node of an element.
  • childNodes: Gets all child nodes (including element, text, and comment nodes).
  • children: Gets only child elements.
  • firstChild & lastChild: Get the first and last child node. May return text or comment nodes.
  • firstElementChild & lastElementChild: Modern properties to get the first and last child element, skipping text/comment nodes.

Sibling Relationships

  • Sibling Elements: Elements that share the same parent.

Properties for sibling access:

  • previousSibling & nextSibling: Get the previous and next sibling node. May return text or comment nodes.
  • previousElementSibling & nextElementSibling: Modern properties to get the previous and next sibling element, skipping text/comment nodes.

Regular Expressions

Basic Usage

  1. Define a Pattern
    const pattern = /expression/
    
    • The / / delimiters denote a regex literal.
    • A regular expression is an object.
  2. Using the Regex
    • The test() method checks if the regex matches a specified string.
    • Returns true on a match, otherwise false.
<script>
    const text = 'JavaScript programming';
    const regexPattern = /Java/;

    console.log(regexPattern.test(text)); // true
    console.log(regexPattern.test('Python coding')); // false
</script>

Metacharacters

  1. Literal Characters: Most characters match themselves (e.g., letters, digits).
  2. Metacharacters (Special Characters): Characters with special meanings, offering powerful pattern matching.
    • Example: Matching lowercase letters: /[a-z]/ vs. listing all letter.

Boundary Assertions

Boundary characters define position within a string.

Using ^ and $ together anforces an exact match.

<script>
    // ^ matches the start of a string
    const startPattern = /^web/;
    console.log(startPattern.test('web dev')); // true
    console.log(startPattern.test('dev web')); // false

    // $ matches the end of a string
    const endPattern = /web$/;
    console.log(endPattern.test('web dev')); // false
    console.log(endPattern.test('dev web')); // true

    // ^ and $ together for exact match
    const exactPattern = /^web$/;
    console.log(exactPattern.test('web')); // true
    console.log(exactPattern.test('web dev')); // false
</script>

Quantifiers

Quantifiers specify how many times a pattern should repeat.

Important: Do not include spaces around the comma in {n,m}.

<script>
    // * : 0 or more times
    const regA = /^w*$/;
    console.log(regA.test('')); // true
    console.log(regA.test('www')); // true

    // + : 1 or more times
    const regB = /^w+$/;
    console.log(regB.test('')); // false
    console.log(regB.test('w')); // true

    // ? : 0 or 1 time
    const regC = /^w?$/;
    console.log(regC.test('')); // true
    console.log(regC.test('ww')); // false

    // {n} : exactly n times
    const regD = /^w{3}$/;
    console.log(regD.test('ww')); // false
    console.log(regD.test('www')); // true

    // {n,} : n or more times
    const regE = /^w{2,}$/;
    console.log(regE.test('w')); // false
    console.log(regE.test('www')); // true

    // {n,m} : between n and m times (inclusive)
    const regF = /^w{2,4}$/;
    console.log(regF.test('w')); // false
    console.log(regF.test('www')); // true
    console.log(regF.test('wwwww')); // false
</script>

Character Classes

Character classes [...] define a set of characters to match.

<script>
    // [abc] matches any single character: a, b, or c.
    const class1 = /^[abc]$/;
    console.log(class1.test('b')); // true
    console.log(class1.test('ab')); // false

    // [a-z] uses a hyphen for a range of characters.
    const class2 = /^[a-z]$/;
    console.log(class2.test('m')); // true
    console.log(class2.test('5')); // false

    // Combine ranges
    const class3 = /^[a-zA-Z0-9]$/;
    console.log(class3.test('Z')); // true
    console.log(class3.test('5')); // true

    // Example: Username 6-16 chars, letters, digits, underscore
    const usernamePattern = /^[a-zA-Z0-9_]{6,16}$/;
    console.log(usernamePattern.test('user_123')); // true
    console.log(usernamePattern.test('abc')); // false

    // [^...] Negation - matches any single character NOT in the set.
    const notClass = /^[^a-z]$/;
    console.log(notClass.test('a')); // false
    console.log(notClass.test('9')); // true
</script>

Character Class Shorthands

Predefined sets for common patterns like digits (\d) or word characters (\w).

Replacement and Flags

The replace() method performs string substitution.

<script>
    const sentence = 'Learn JavaScript. Master JavaScript.';
    // Replaces only the first occurrence
    const result1 = sentence.replace(/JavaScript/, 'JS');
    console.log(result1); // 'Learn JS. Master JavaScript.'
</script>

Flags modify regex behavior.

  • i (ignore case): Makes the match case-insensitive.
  • g (global): Replaces all matches, not just the first.
<script>
    const sentence = 'Learn JavaScript. Master JavaScript.';
    // Replaces all occurrences globally
    const result2 = sentence.replace(/JavaScript/g, 'JS');
    console.log(result2); // 'Learn JS. Master JS.'

    // Case-insensitive replacement
    const text2 = 'Hello WORLD, hello World';
    const result3 = text2.replace(/hello/gi, 'Hi');
    console.log(result3); // 'Hi WORLD, Hi World'
</script>

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.