Js Regexp in JavaScript
? JavaScript RegExp (Regular Expressions)
A RegExp (Regular Expression) is a pattern used to match character combinations in strings. It's super useful for searching, validating, and manipulating text.
Creating a RegExp
1. Using literal syntax:
const regex = /hello/i; // 'i' for case-insensitive2. Using constructor:
const regex = new RegExp('hello', 'i');Common Methods with RegExp
Given:
const str = "Hello World!";const regex = /hello/i;test()— tests if pattern exists, returnstrueorfalse:
regex.test(str); // trueexec()— returns details about the match ornull:
const result = regex.exec(str);console.log(result);// Output example:// ["Hello", index: 0, input: "Hello World!", groups: undefined]String.match()— gets all matches (returns array or null):
const matches = str.match(/o/g); // ['o', 'o']String.replace()— replaces matched parts:
const newStr = str.replace(/world/i, "JS");console.log(newStr); // "Hello JS!"RegExp Flags
| Flag | Meaning |
|---|---|
g | Global search (all matches) |
i | Case-insensitive search |
m | Multi-line search |
u | Unicode support |
s | Dot matches newline |
y | Sticky search |
Example: Validate Email Format
const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$/i;console.log(emailRegex.test("test@example.com")); // trueconsole.log(emailRegex.test("invalid-email")); // falseExample: Extract Numbers from String
const str = "My phone number is 123-456-7890.";const numbers = str.match(/\d+/g);console.log(numbers); // ["123", "456", "7890"]Summary
RegExp helps find patterns in strings.
Use
test(),exec(),match(),replace()for common tasks.Use flags for behavior control.
Want me to help you build a specific regex or explain regex syntax like quantifiers, groups, or character classes?