Manipulating DOM Nodes and Using Regular Expressions in JavaScript
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
- Define a Pattern
const pattern = /expression/- The
/ /delimiters denote a regex literal. - A regular expression is an object.
- The
- Using the Regex
- The
test()method checks if the regex matches a specified string. - Returns
trueon a match, otherwisefalse.
- The
<script>
const text = 'JavaScript programming';
const regexPattern = /Java/;
console.log(regexPattern.test(text)); // true
console.log(regexPattern.test('Python coding')); // false
</script>
Metacharacters
- Literal Characters: Most characters match themselves (e.g., letters, digits).
- Metacharacters (Special Characters): Characters with special meanings, offering powerful pattern matching.
- Example: Matching lowercase letters:
/[a-z]/vs. listing all letter.
- Example: Matching lowercase letters:
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>