Javascript regex
Created By: chatGPT
JavaScript utilizes regular expressions (regex) to search, match, and manipulate strings. Regular expressions are patterns that provide a powerful way to perform pattern matching on strings. They can be used for tasks like validation, search and replace, and string extraction.
// Example of a regular expression in JavaScript
const regex = /\d+/;
const str = 'There are 123 cats and 456 dogs.';
const matches = str.match(regex);
console.log(matches); // Output: ['123']
To create a regex in JavaScript, you can use either literal notation or constructor notation. Literal notation is often preferred for its simplicity.
// Literal notation
const literalRegex = /hello/;
// Constructor notation
const constructorRegex = new RegExp('hello');
You can enhance regex patterns with metacharacters, which have special meanings. For example, the
.
character matches any single character, while ^
asserts position at the start of a string, and $
asserts position at the end.// Matches any string that starts with 'Hello' and ends with 'World'
const pattern = /^Hello.*World$/;
const testString = 'Hello, how are you? Welcome to the World';
console.log(pattern.test(testString)); // Output: false
Regex also allows for quantifiers to specify how many instances of a character or group must be present. Common quantifiers include
*
(zero or more), +
(one or more), and {n}
(exactly n times).// Matches any string with at least one digit
const digitPattern = /\d+/;
console.log(digitPattern.test('abc123')); // Output: true
You can also use character classes to match a set of characters. For example,
[abc]
matches any single character 'a', 'b', or 'c'. To match any character except those in the class, use ^
inside the brackets: [^abc]
.// Matches any character that is not a vowel
const nonVowelPattern = /[^aeiou]/g;
const testStr = 'Hello World';
console.log(testStr.match(nonVowelPattern)); // Output: ['H', 'l', 'l', ' ', 'W', 'r', 'l', 'd']
When working with regex, you can also employ groups to capture specific parts of your match. Parentheses
()
create a group and allow you to extract and refer back to matched sub-patterns.// Captures the first word and the digits that follow
const groupPattern = /^(\w+)\s+(\d+)/;
const input = 'Age: 30';
const result = input.match(groupPattern);
console.log(result); // Output: ['Age: 30', 'Age', '30']