Regular Expressions Kya Hota Hai?
Regular Expressions yaani “Regex” ek powerful tool hai JavaScript mein jo strings ke pattern matching ke liye use hota hai. Iska use tab kiya jaata hai jab hume kisi string mein specific characters, words, ya patterns dhoondhne, replace karne, ya validate karne hote hain.
Regex ka syntax hota hai:
/pattern/flags
Jaise /hello/i
ek pattern hai jo case-insensitive tarike se “hello” ko dhoondhega.
JavaScript mein test()
, match()
, replace()
, search()
jaise methods ke through regex ka use hota hai.
Example: Agar email address validate karna ho to regex se check kar sakte hain ki format sahi hai ya nahi.
Regex ka use form validation, data filtering, aur string manipulation jaise tasks mein hota hai.
Regex seekhna thoda tricky hota hai, lekin once mastered, bahut hi useful hai.
Basic Syntax of RegEx:
let pattern = /abc/;
Yahaan /abc/
ek Regular Expression hai.
/
ke beech likha hua text hi actual pattern hota hai.
Kaise Banate Hain RegEx?
JavaScript mein 2 tareeke se RegEx banaya ja sakta hai:
- Literal Notation:
let regex1 = /hello/;
- Constructor Method:
let regex2 = new RegExp("hello");
RegEx Methods in JavaScript:
- test() – The
test()
method is used to check whether a regular expression pattern exists in a given string. It returns a Boolean value:true
if the pattern is found, andfalse
if not. It’s typically used when you only want to confirm the presence or absence of a pattern, not extract the actual match.let regex = /apple/; regex.test("I love apple"); // true
- exec() – The
exec()
method executes a search for a match in a specified string using a regular expression. It returns an array containing the matched text and other related details like index and input, ornull
if no match is found. It’s useful when you need detailed match information from a regular expression.let regex = /apple/; regex.exec("I love apple"); // ["apple"]
- match() – The
match()
method is used with strings to retrieve matches based on a regular expression. It returns an array of all matched results ornull
if no match is found. It’s great for finding multiple matches when the global (/g
) flag is used in the regular expression, unlikeexec()
."I love apple".match(/apple/); // ["apple"]
- replace() – The
replace()
method searches a string for a match against a regular expression and replaces the matched substring with a new one. It returns a new string with the replacement. You can use it for single or global replacements depending on the regular expression flags like/g
for multiple replacements."I love apple".replace(/apple/, "banana"); // "I love banana"
- search() – The
search()
method searches for a match between a regular expression and a specified string. It returns the index of the first match or-1
if no match is found. It’s a quick way to locate the position of a pattern within a string, without retrieving the actual match data."I love apple".search(/apple/); // 7
Common RegEx Symbols (Metacharacters):
Symbol | Meaning | Example | Output |
---|---|---|---|
. | Any character except newline | /a.c/ | “abc”, “a1c” |
^ | Start of string | /^Hello/ | Matches if string starts with Hello |
$ | End of string | /end$/ | Matches if string ends with “end” |
* | 0 or more times | /lo*/ | “lo”, “loo”, “looo” |
+ | 1 or more times | /lo+/ | “lo”, “loo”, “looo” |
? | 0 or 1 time | /lo?/ | “l”, “lo” |
[] | Match any one character | /[aeiou]/ | any vowel |
() | Grouping | /(abc)+/ | “abc”, “abcabc” |
Character Classes:
Symbol | Meaning |
---|---|
\d | Any digit (0-9) |
\D | Non-digit |
\w | Word character (a-z, A-Z, 0-9, _) |
\W | Non-word character |
\s | Whitespace |
\S | Non-whitespace |
Example 1: Email Validation :
Email validation (JavaScript) ka matlab hai kisi email address ko check karna ki wo sahi format mein hai ya nahi, jaise [email protected]
. JavaScript mein hum email validate karne ke liye Regular Expressions (RegEx) ka use karte hain. Ye ek aisa pattern hota hai jo batata hai ki email valid hai ya nahi. Validation ensure karta hai ki user galat ya incomplete email na dale. JavaScript se frontend par hi turant feedback mil jata hai, bina server tak data bheje. Isse user experience improve hota hai aur spam ya invalid entries ko roka ja sakta hai.
let emailPattern = /^[a-zA-Z0-9._]+@[a-z]+\.[a-z]{2,4}$/;
emailPattern.test("[email protected]"); // true
Example 2: Mobile Number Validation (10 digits) :
Mobile Number Validation (10 digits) JavaScript mein ek aisi technique hai jisse hum ensure karte hain ki user ne jo mobile number input kiya hai, woh valid format mein hai ya nahi. Is case mein, valid ka matlab hai sirf 10 digits hone chahiye — na kam, na zyada. JavaScript mein hum regular expression (RegEx) ka use karke check karte hain ki number sirf digits ka ho aur uski length exactly 10 ho. Agar number is condition ko fulfill karta hai toh valid mana jata hai, warna error message dikhaya jata hai. Yeh validation user input secure aur sahi banata hai.
let phonePattern = /^[0-9]{10}$/;
phonePattern.test("9876543210"); // true
RegEx Kha Use Hota Hai?
JavaScript mein RegEx (Regular Expression) ek powerful tool hai jo text ya strings ko match, search, aur manipulate karne ke liye use hota hai. Ye khas tor par form validation mein kaam aata hai jaise ki email, password ya phone number check karna. Search operations mein kisi specific word ya pattern ko dhoondhne ke liye RegEx bahut helpful hota hai. String formatting mein bhi iska use hota hai jaise unwanted spaces hataana ya proper format set karna. Data cleaning ke liye RegEx se galat ya extra characters ko remove kiya ja sakta hai. JavaScript mein web scraping ya text extraction ke dauraan bhi ye use hota hai, jahan hume kisi webpage se specific information extract karni hoti hai. Overall, RegEx se JavaScript developers complex string tasks ko efficiently handle kar paate hain.
Tips:
- RegEx powerful hota hai but thoda confusing bhi ho sakta hai initially.
- Practice zaruri hai. Online tools jaise regex101.com aapko visualize karne mein help karenge.
- Har symbol ka exact meaning yaad rakhna important hai.
Flags in RegEx:
Flags pattern ke behavior ko control karte hain:
- g – Global search (sare matches find karega)
- i – Case-insensitive search
- m – Multi-line search
Example:
const regex = /hello/gi;
const str = "Hello hello HELLO";
console.log(str.match(regex)); // ["Hello", "hello", "HELLO"]
JavaScript mein Regular Expressions ek bahut hi powerful aur flexible tool hai jo string manipulation aur validation ko easy banata hai. Web development ya data validation mein kaam karne wale logon ke liye RegEx seekhna zaroori hai. Thoda practice aur examples se aap easily expert ban sakte ho.
Quiz: Test Your Knowledge on JavaScript Regular Expressions (RegEx)
Bonus: Practical Application!
Aaj hi JavaScript me Regular Expressions ka istemal karke dekhein!
Regular Expressions (RegEx) ko sahi tareeke se samajhne ke liye different patterns jaise match, test, replace, search, aur modifiers jaise g, i, m ka upayog karein.
Inka upyog karke aap strings ke saath complex searching aur text manipulation easily kar sakte hain.