Regular Expressions (RegEx) in JavaScript are patterns used to match, search, and replace text. They are powerful tools for validating input, parsing strings, and finding patterns in text.
This blog explains RegEx syntax, methods, and practical examples.
⭐ 1. Creating Regular Expressions
1. Using Literal Syntax
let pattern = /hello/;
console.log(pattern.test("hello world")); // true
2. Using RegExp Constructor
let pattern = new RegExp("hello");
console.log(pattern.test("hello world")); // true
⭐ 2. Common RegEx Patterns
| Pattern | Description | Example |
|---|---|---|
^ | Start of string | /^Hello/ |
$ | End of string | /world$/ |
. | Any character | /h.llo/ |
* | 0 or more occurrences | /lo*/ |
+ | 1 or more occurrences | /lo+/ |
? | 0 or 1 occurrence | /lo?/ |
\d | Any digit | /\d/ |
\w | Any word character | /\w/ |
\s | Any whitespace | /\s/ |
[...] | Character set | /[aeiou]/ |
⭐ 3. RegEx Methods in JavaScript
test()
Checks if a pattern exists in a string.
let pattern = /world/;
console.log(pattern.test("Hello world")); // true
exec()
Returns the matched string or null.
let result = /world/.exec("Hello world");
console.log(result[0]); // world
String.match()
let str = "I love JS";
let matches = str.match(/love/);
console.log(matches[0]); // love
String.replace()
let str = "Hello world";
let newStr = str.replace(/world/, "JavaScript");
console.log(newStr); // Hello JavaScript
String.search()
let str = "Hello world";
console.log(str.search(/world/)); // 6 (index of match)
String.split()
let str = "apple,banana,mango";
let fruits = str.split(/,/);
console.log(fruits); // ["apple","banana","mango"]
⭐ 4. Practical Example: Email Validation
function validateEmail(email){
let pattern = /^[^ ]+@[^ ]+\.[a-z]{2,3}$/;
return pattern.test(email);
}
console.log(validateEmail("test@example.com")); // true
console.log(validateEmail("test@.com")); // false
⭐ Conclusion
Regular expressions are powerful and versatile for working with text in JavaScript. They allow developers to validate input, search patterns, and manipulate strings efficiently.
📌 Citations
🔗 View other articles about Javascript:
https://savanka.com/category/learn/js/
🔗 External Javascript Documentation:
https://www.w3schools.com/js/