A regular expression is a pattern of characters. The pattern is used to do pattern-matching “search-and-replace” functions on text.
Method:
- test: The test() method tests for a match in a string. If it finds a match, it returns true, otherwise it returns false.
var text = "The best things in life are free"; var pattern = /e/; var result = pattern.test(text);
2. exec or match: The exec() method tests for a match in a string. If it finds a match, it returns a result array, otherwise, it returns null.
var text = "The best things in life are free"; var pattern = /e/; var result = text.match(pattern);
3. Replace: To replace pattern in characters, use replace() – Replace special characters
var values = '&677,431,444,98777'; var result=values.replace(/({[@!#$%*_^\&]})|,/g, ''); console.log(result);
Pattern Designing & Pattern Concept:
Simple Pattern :
- [abc] – a,b or c
- [^abc] – Any character except a,b or c
- [a-z] – a to z
- [A-Z] – A to Z
- [a-z A-Z] – a to z or A-Z
- [0-9] – 0-9 digit
Meta Characters:
- \d – Digit [0-9]
- \D – Not a digit [^0-9]
- \w – Word Charecter [a-z A-Z 0-9 _)
- \W – Not a Word charecter
- \s – White space (space, tab, newline)
- \S – Not Whitespace
- ^ – Beginning of string
- $ – End of string
- () – Group
- | – Either or
Quantifiers:
- [ ]? – Occurs 0 or 1 Times
- [ ]+ – Occurs 1 or More times
- [ ]* – Occurs 0 or More times
- [ ]{n} – Occurs n or more times
- [ ]{y,z} – Occurs Starts with y & Ends with z
Testing Tools
Question & Answer:
- Accept only numbers in string fields?
- Accept only Characters in string fields?
- Check whether strings have a special character or not.
- Fields should only accept email addresses.
- Replace all special character
No responses yet