In JavaScript, a regular expression can be created in two ways:
let regex = /pattern/;
RegExp
constructor:let regex = new RegExp('pattern');
Both methods do the same thing, but regular expression literals are more common and easier to use.
let regexLiteral = /hello/; // Regular Expression literal
let regexConstructor = new RegExp('hello'); // Regular Expression constructor
console.log(regexLiteral.test('hello world')); // Output: true
console.log(regexConstructor.test('hello world')); // Output: true
A regular expression consists of a pattern and optional flags.
^
: Matches the start of the string.$
: Matches the end of the string.\d
: Matches any digit.\s
: Matches any whitespace character.g
: Global search (finds all matches).i
: Case-insensitive search.m
: Multiline matching (affects ^
and $
).let regex = /hello/i; // Case-insensitive search
console.log(regex.test('HELLO')); // Output: true
console.log(regex.test('hello')); // Output: true
JavaScript provides several string methods that work with regular expressions:
match()
: Returns an array of all matches found in the string, or null
if no match is found.search()
: Returns the index of the first match, or -1
if no match is found.replace()
: Replaces a match in the string with a new substring.split()
: Splits the string into an array of substrings based on the pattern.match()
let str = 'The quick brown fox jumps over the lazy dog';
let regex = /fox/;
let result = str.match(regex);
console.log(result); // Output: ['fox']
search()
let str = 'The quick brown fox jumps over the lazy dog';
let regex = /fox/;
let index = str.search(regex);
console.log(index); // Output: 16
replace()
let str = 'The quick brown fox jumps over the lazy dog';
let regex = /fox/;
let newStr = str.replace(regex, 'cat');
console.log(newStr); // Output: 'The quick brown cat jumps over the lazy dog'
split()
let str = 'The quick brown fox jumps over the lazy dog';
let regex = /\s+/;
let result = str.split(regex);
console.log(result); // Output: ['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']
let str = 'The quick brown fox jumps over the lazy dog';
let regexMatch = /fox/;
let matchResult = str.match(regexMatch);
console.log(matchResult); // Output: ['fox']
let regexSearch = /fox/;
let searchResult = str.search(regexSearch);
console.log(searchResult); // Output: 16
let regexReplace = /fox/;
let replaceResult = str.replace(regexReplace, 'cat');
console.log(replaceResult); // Output: The quick brown cat jumps over the lazy dog
let regexSplit = /\s+/;
let splitResult = str.split(regexSplit);
console.log(splitResult); // Output: ['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']